	//
//  ConsultingChatViewController.m
//  安好
//
//  Created by 冯凯 on 14-8-26.
//  Copyright (c) 2014年 冯凯. All rights reserved.
//
#import "SystemMessageCenter.h"
#import "ConsultingChatViewController.h"
#import "LCPatientDetailCell.h"
#import "LCSendImageCell.h"
#import "LCSendTextCell.h"
#import "LCSendVoiceCell.h"
#import "LCSendTextSelfCell.h"
#import "AppDelegate.h"
#import "NSObject+DataParse.h"
#import "LCStatusBarOverlay.h"
#import "UIImageView+MJWebCache.h"
#import "ChatContent.h"
#import "PeerList.h"
#import "ConsultList.h"
#import "AppDelegate.h"
#import "ConsultQuestionView.h"
#import "AFURLSessionManager.h"
#import "DocInfoViewController.h"
#import "MyConsultListViewController.h"
#import "BaseNavigation.h"
#import "ReportViewController.h"
#import "KeyWordsView.h"
#import "RelatedQustionsViewController.h"
#import "MethodViewCell.h"
#import "FirendDetailViewController.h"
#import "DocCommentViewController.h"
#import "RelatedListViewController.h"
#import "FMDatabaseQueue.h"
#import "XHImageViewer.h"
#import "UIView+XHRemoteImage.h"
#import "IFTweetLabel.h"
#import "RelatedIssuesView.h"
#import "RelatedHeaderVeiw.h"
#import "RelatedFoottView.h"
#import "YYImagePickerViewController.h"
@interface ConsultingChatViewController ()<TapMessageImageDelegate,UIAlertViewDelegate,ChatDelegate,UITextViewDelegate,JSMessageInputViewDelegate,SendVoiceDelegate,SendMessageDelegate,SelectPhoto,OverDelegate,SendJiahaodan,XHImageViewerDelegate,IFTweetLabelDelegate,UIGestureRecognizerDelegate,RelatedIssuseDelegate,RelatedMoreDelegate,YYImagePickerViewControllerDelegate>
{
    
}
@end

@implementation ConsultingChatViewController
{
    BOOL isEdit;
    BOOL isOverConsult;
    UIButton * zanButton;
    BOOL isSecondClick;
    UIButton *rightBtn;
//    KeyWordsView *keyWordview;
    NSMutableArray *imageArray;
    NSInteger pagecount;
    NSMutableArray *Views;
    RelatedIssuesView *relate;
    NSString *tempdateline;
    //粘贴板的文字；
    NSString *boarString;
}
@synthesize keyboardController;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
/**
 *  键盘的通知
 */
- (void)initializeData{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}
- (void)keyboardWillShow:(NSNotification *)notification
{
}
- (void)keyboardWillHide:(NSNotification *)notification
{
    NSInteger duration=[[notification.userInfo valueForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        self.tableView.frame=CGRectMake(0, 0, kScreenWidth, kScreenHeight-64-45);
        if (self.dataArray.count > 0) {
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataArray.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        }

    } completion:^(BOOL finished) {
    }];
}
- (void)keyboardWillChangeFrame:(NSNotification *)notification
{
    CGRect rect =[[notification.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSInteger duration=[[notification.userInfo valueForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        self.tableView.frame=CGRectMake(0,0, kScreenWidth, kScreenHeight-64-45-rect.size.height);
        if (self.dataArray.count > 0) {
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataArray.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        }
    } completion:^(BOOL finished) {
    }];
}

-(void)viewDidDisappear:(BOOL)animated
{

    self.isFromConsult=NO;
    [keyboardController.messageInputView.inputTextView resignFirstResponder];
    [keyboardController hiddenCustomKeyboardToolAnimation];
    NSString * userIsLogin =  [[UserManager shareInstance] getUserIsLogin];
    if ([userIsLogin length] == 0 || [[UserManager shareInstance]getUserIsLogin ] == nil) {
        return;
    }
    dispatch_queue_t queue = dispatch_get_main_queue();
    dispatch_async(queue, ^{
        if (self.isFromwhere==kWCEnterIntoConsultChatNoPeer) {
            ConsultList *chatItem=[[ConsultList getTheLastOneWithQid:self.qid] objectAtIndex:0];
            if ([chatItem.noread isEqualToString:@"1"]) {
                [ConsultList resetUnreadCountWithUid:self.qid];
            }
        }else if(self.isFromwhere==kWCEnterIntoConsultChatPeer)
        {
            [PeerList resetUnreadCountWithUid:self.touid];
        }
    });
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreSystemNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"kill" object:nil];
    if ([self.avPlay isPlaying]) {
        [self.avPlay stop];
    }
    if ([self.avPlay2 isPlaying]) {
        [self.avPlay2 stop];
    }
    if ([self.sendPlay isPlaying]) {
        [self.sendPlay stop];
    }
    //移除代理
    AppDelegate *app=(AppDelegate *)[[UIApplication sharedApplication] delegate];
    app.chatDelegate=nil;
    [timer invalidate];
}
- (AppDelegate *)app
{
    AppDelegate *app=(AppDelegate *)[[UIApplication sharedApplication] delegate];
    app.chatDelegate=self;
    return app;
}
#pragma mark chatDelegate 聊天代理
- (void)receiveMessage:(AppDelegate *)appD Message:(id)message
{

    NSDictionary *dict = [YXJSON dictionaryOrArrayWithJSONSString:message];
    NSMutableDictionary *MutDic=[NSMutableDictionary dictionaryWithDictionary:dict];
    [MutDic setValue:@"2" forKey:@"messageDirection"];
    NSString *messageType;
    if ([[dict valueForKey:@"message"] length] > 0) {
        messageType = @"1";
    } else if ([[dict valueForKey:@"pic"] length] > 0) {
        messageType = @"2";
    } else {
        messageType = @"3";
    }
    [MutDic setValue:messageType forKey:@"messageType"];
    //判断同行or非同行 。type=1同行；type=2医患关系。
    ChatContent *chat=[[ChatContent alloc]initWithDictionary:MutDic];
    NSString *readStatus;
    if ([[dict objectForKey:@"type"] intValue] == 1) {
        NSString *touid=[NSString stringWithFormat:@"%@",[dict valueForKey:@"uid"]];
        NSString *comUid=[NSString stringWithFormat:@"%@",self.touid];
        if ([touid isEqualToString:comUid]) {
            readStatus=@"0";
            //如果结束了，在受到消息打开输入框
            keyboardController.messageInputView.hidden=NO;
        }else
        {
            LCStatusBarOverlay *statusbar=[LCStatusBarOverlay shared];
            [statusbar hidenMessageLabel];
            [statusbar analysisIMmessage:message];
            [statusbar showMessageLabel];
            readStatus=@"1";
        }
        
        [PeerList updatePeerList:message withReadStatus:readStatus withSuccess:@"1" withMessageDirection:@"1"];

        dispatch_queue_t queue = dispatch_get_main_queue();
        dispatch_async(queue, ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                //加入耗时操作
                CGSize size;
                if (chat.pic.length>0) {
                    size=[ChatContent downloadImageSizeWithURL:chat.pic];
                    chat.width=[NSString stringWithFormat:@"%f",size.width];
                    chat.heigth=[NSString stringWithFormat:@"%f",size.height];
                    
                    NSString *touid=[NSString stringWithFormat:@"%@",[dict valueForKey:@"uid"]];
                    NSString *uid=[NSString stringWithFormat:@"%@",self.touid];
                    if ([touid isEqualToString:uid]) {
                        [self.dataArray addObject:chat];
                        [self skipTableviewBottom];
                    }
                    else
                    {
                    }
                    
                    NSDictionary *messageDic=[YXJSON dictionaryOrArrayWithJSONSString:message];
                    [messageDic setValue:[NSString stringWithFormat:@"%f",size.width] forKey:@"width"];
                    [messageDic setValue:[NSString stringWithFormat:@"%f",size.height] forKey:@"heigth"];
                    [ChatContent insertChatMessageItem:[YXJSON JSONStringWithDictionaryOrArray:messageDic] Andsuccess:@"1" AndMessageDirection:@"2"];
                }
                else{
                    
                    NSString *uid=[NSString stringWithFormat:@"%@",[dict valueForKey:@"uid"]];
                    NSString *touid=[NSString stringWithFormat:@"%@",self.touid];
                    if ([uid isEqualToString:touid]) {
                        [self.dataArray addObject:chat];
                        [self skipTableviewBottom];
                    }
                    [ChatContent insertChatMessageItem:message Andsuccess:@"1" AndMessageDirection:@"2"];
                }
            });
        });
    }else
    {
        if ([[NSString stringWithFormat:@"%@",[dict valueForKey:@"qid"]] isEqualToString:self.qid]) {
            
            self.touid=[NSString stringWithFormat:@"%@",[dict valueForKey:@"uid"]];
            self.doctoruid=[NSString stringWithFormat:@"%@",[dict valueForKey:@"uid"]];

            NSString *meth=[NSString stringWithFormat:@"%@",[dict valueForKey:@"method"]];
            if ([meth isEqualToString:@"9"]) {
                [self loadMyConsultQuestionInfo];
                return;
            }
            readStatus=@"0";
            keyboardController.messageInputView.hidden=NO;
        }else
        {
            LCStatusBarOverlay *statusbar=[LCStatusBarOverlay shared];
            [statusbar hidenMessageLabel];
            [statusbar analysisIMmessage:message];
            [statusbar showMessageLabel];
            NSString *meth=[NSString stringWithFormat:@"%@",[dict valueForKey:@"method"]];
            if ([meth isEqualToString:@"9"]) {
                return;
            }
            readStatus=@"1";
        }
        dispatch_queue_t queue = dispatch_get_main_queue();
        dispatch_async(queue, ^{
            
            dispatch_async(dispatch_get_main_queue(), ^{
                {
                    //加入耗时操作
                    CGSize size;
                    if (chat.pic.length>0) {
                        size=[ChatContent downloadImageSizeWithURL:chat.pic];
                        chat.width=[NSString stringWithFormat:@"%f",size.width];
                        chat.heigth=[NSString stringWithFormat:@"%f",size.height];
                        
                        if ([[NSString stringWithFormat:@"%@",[dict valueForKey:@"qid"]] isEqualToString:self.qid]) {
                            [self.dataArray addObject:chat];
//                            [self skipTableviewBottom];
                        }
                        
                        NSDictionary *messageDic=[YXJSON dictionaryOrArrayWithJSONSString:message];
                        [messageDic setValue:[NSString stringWithFormat:@"%f",size.width] forKey:@"width"];
                        [messageDic setValue:[NSString stringWithFormat:@"%f",size.height] forKey:@"heigth"];
                        [ChatContent insertChatMessageItem:[YXJSON JSONStringWithDictionaryOrArray:messageDic] Andsuccess:@"1" AndMessageDirection:@"2"];
                    }
                    else{
                        [ChatContent insertChatMessageItem:message Andsuccess:@"1" AndMessageDirection:@"2"];
                        
                        
                        NSString *toqid=[NSString stringWithFormat:@"%@",[dict valueForKey:@"qid"]];
                        NSString *qid=[NSString stringWithFormat:@"%@",self.qid];
                        if ([toqid isEqualToString:qid]) {
                            [self.dataArray addObject:chat];
//                            [self skipTableviewBottom];
                            keyboardController.messageInputView.hidden=NO;
                            [rightBtn setTitle:@"结束咨询" forState:UIControlStateNormal];
                            self.overView.hidden=YES;
                        }
                    }
                }
                
                if (self.dataArray.count==1) {
                    self.tableView.contentOffset=CGPointMake(0, 0);
                    self.tableView.frame=CGRectMake(0, 0, kScreenWidth, kScreenHeight-64-45);
                    relate.hidden=YES;
                    [self loadMyConsultQuestionInfo];
                }
                else if(self.dataArray.count>1)
                {
                    relate.hidden=YES;
                    if (keyboardController.messageInputView.hidden==YES) {
                        self.tableView.frame=CGRectMake(0, 0, kScreenWidth, kScreenHeight-64-45);
                    }
                    else
                    {
                        if (self.selfOver.length>0&&[self.selfOver isEqualToString:@"1"]) {
                            self.tableView.frame=CGRectMake(0, 0, kScreenWidth, kScreenHeight-64-45);
                        }else{
                            self.tableView.frame=CGRectMake(0, 0, kScreenWidth, self.tableView.frame.size.height);
                        }
                    }
                }
                [self skipTableviewBottom];
            });
            [ConsultList updateConsultList:message withReadStatus:readStatus withSuccess:@"1" withMessageDirection:@"2"];
        });
    }
}
- (void)receiveRemoteNotificationMessage:(AppDelegate *)appD Message:(id)message
{
    NSDictionary *dict = [YXJSON dictionaryOrArrayWithJSONSString:message];
    //遍历消息内容数组，排序后将消息插入数据库（如果和当前用户是同一人，并展示聊天消息）
    NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *sqlPath=[docPath stringByAppendingPathComponent:@"mydatabase.sqlite"];
    FMDatabaseQueue * queue = [FMDatabaseQueue databaseQueueWithPath:sqlPath];
    dispatch_queue_t q1 = dispatch_queue_create("queue1", NULL);
//    dispatch_queue_t q2 = dispatch_queue_create("queue2", NULL);
    dispatch_async(q1, ^{
        NSArray * array1 = [[[dict objectForKey:@"history"] allKeys]sortedArrayUsingSelector:@selector(compare:)];
        for (int index=0; index<array1.count; index++) {
            NSString *keys=[array1 objectAtIndex:index];
            if([[[[dict objectForKey:@"history"] objectForKey:keys] objectForKey:@"action"] isEqualToString:@"send"])
            {
                //在其他界面收到聊天消息，只进行存取数据（2个表）
                NSMutableDictionary *MutDic=[NSMutableDictionary dictionaryWithDictionary:[[dict objectForKey:@"history"] objectForKey:keys]];
                [MutDic setValue:@"2" forKey:@"messageDirection"];
                NSString *messageType;
                if ([[[[dict objectForKey:@"history"] objectForKey:keys] valueForKey:@"message"] length] > 0) {
                    messageType = @"1";
                } else if ([[[[dict objectForKey:@"history"] objectForKey:keys] valueForKey:@"pic"] length] > 0) {
                    messageType = @"2";
                } else {
                    messageType = @"3";
                }
                [MutDic setValue:messageType forKey:@"messageType"];
                //判断同行or非同行 。type=1同行；type=2医患关系。
                ChatContent *chat=[[ChatContent alloc]initWithDictionary:MutDic];
                NSString *readStatus;
                if ([[[[dict objectForKey:@"history"] objectForKey:keys]  objectForKey:@"type"] intValue] == 1) {
                    if ([[NSString stringWithFormat:@"%@",[[[dict objectForKey:@"history"] objectForKey:keys] valueForKey:@"uid"]] isEqualToString:self.touid]) {
                        readStatus=@"0";
                        self.touid=[NSString stringWithFormat:@"%@",[[[dict objectForKey:@"history"] objectForKey:keys] valueForKey:@"uid"]];
                        keyboardController.messageInputView.hidden=NO;
                        self.tableView.frame=CGRectMake(0, 0, kScreenWidth, self.tableView.frame.size.height);
                    }else
                    {
                        readStatus=@"1";
                    }
                    CGSize size;
                    NSDictionary *dicM=[[dict objectForKey:@"history"] objectForKey:keys];
                    if (chat.pic.length>0) {
                        size=[ChatContent downloadImageSizeWithURL:chat.pic];
                        chat.width=[NSString stringWithFormat:@"%f",size.width];
                        chat.heigth=[NSString stringWithFormat:@"%f",size.height];
                        [dicM setValue:chat.width forKey:@"width"];
                        [dicM setValue:chat.heigth forKey:@"heigth"];
                    }
                    if ([[NSString stringWithFormat:@"%@",[dicM valueForKey:@"uid"]] isEqualToString:self.touid]) {
                        [self.dataArray addObject:chat];
                    }
                    else
                    {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            LCStatusBarOverlay *statusbar=[LCStatusBarOverlay shared];
                            [statusbar hidenMessageLabel];
                            [statusbar analysisIMmessage:[YXJSON JSONStringWithDictionaryOrArray:[[dict objectForKey:@"history"] objectForKey:keys]]];
                            [statusbar showMessageLabel];
                        });
                        
                    }
//                    [self skipTableviewBottom];
                    [queue inDatabase:^(FMDatabase *db) {
                    [ChatContent insertChatMessageItem:[YXJSON JSONStringWithDictionaryOrArray:dicM] Andsuccess:@"1" AndMessageDirection:@"2"];
                    //                    });
                    [PeerList updatePeerList:[YXJSON JSONStringWithDictionaryOrArray:[[dict objectForKey:@"history"] objectForKey:keys]] withReadStatus:readStatus withSuccess:@"1" withMessageDirection:@"2"];
                    }];
                }else
                {
                    
                if ([[NSString stringWithFormat:@"%@",[[[dict objectForKey:@"history"] objectForKey:keys] valueForKey:@"qid"]] isEqualToString:self.qid])
                {
                        readStatus=@"0";
//                        relate.hidden=YES;
                        self.touid=[NSString stringWithFormat:@"%@",[[[dict objectForKey:@"history"] objectForKey:keys] valueForKey:@"uid"]];
                        keyboardController.messageInputView.hidden=NO;
                }else
                {
                        readStatus=@"1";
                }
                    
                NSDictionary *dicm=[[dict objectForKey:@"history"] objectForKey:keys];
                CGSize size;
                if (chat.pic.length>0) {
                            size=[ChatContent downloadImageSizeWithURL:chat.pic];
                            chat.width=[NSString stringWithFormat:@"%f",size.width];
                            chat.heigth=[NSString stringWithFormat:@"%f",size.height];
                            [dicm setValue:chat.width forKey:@"width"];
                            [dicm setValue:chat.heigth forKey:@"heigth"];
                    }
                    
                if ([[NSString stringWithFormat:@"%@",[[[dict objectForKey:@"history"] objectForKey:keys] valueForKey:@"qid"]] isEqualToString:self.qid]){
                        if (self.dataArray.count<=0) {
                            
                            
                            NSString *meth=[NSString stringWithFormat:@"%@",[[[dict objectForKey:@"history"] objectForKey:keys] valueForKey:@"method"]];
                            if ([meth isEqualToString:@"9"]) {
                                [self loadMyConsultQuestionInfo];
                                return;
                            }
                        }
                    [self.dataArray addObject:chat];
                    [queue inDatabase:^(FMDatabase *db) {
                        if ([ConsultList updateConsultList:[YXJSON JSONStringWithDictionaryOrArray:[[dict objectForKey:@"history"] objectForKey:keys]] withReadStatus:readStatus withSuccess:@"1" withMessageDirection:@"2"]) {
                            
                            NSString *meth=[NSString stringWithFormat:@"%@",[[[dict objectForKey:@"history"] objectForKey:keys] valueForKey:@"method"]];
                            if ([meth isEqualToString:@"9"]) {
                                return;
                            }
                            [ChatContent insertChatMessageItem:[YXJSON JSONStringWithDictionaryOrArray:dicm] Andsuccess:@"1" AndMessageDirection:@"2"];
                        }
                        
                    }];

                }else{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            LCStatusBarOverlay *statusbar=[LCStatusBarOverlay shared];
                            [statusbar hidenMessageLabel];
                            [statusbar analysisIMmessage:[YXJSON JSONStringWithDictionaryOrArray:[[dict objectForKey:@"history"] objectForKey:keys]]];
                            [statusbar showMessageLabel];
                        });
                    [queue inDatabase:^(FMDatabase *db) {
                        if ([ConsultList updateConsultList:[YXJSON JSONStringWithDictionaryOrArray:[[dict objectForKey:@"history"] objectForKey:keys]] withReadStatus:readStatus withSuccess:@"1" withMessageDirection:@"2"]) {
                            
                            NSString *meth=[NSString stringWithFormat:@"%@",[[[dict objectForKey:@"history"] objectForKey:keys] valueForKey:@"method"]];
                            if ([meth isEqualToString:@"9"]) {
                                return;
                            }
                            [ChatContent insertChatMessageItem:[YXJSON JSONStringWithDictionaryOrArray:dicm] Andsuccess:@"1" AndMessageDirection:@"2"];
                        }
                        
                    }];

                    }
                    keyboardController.messageInputView.hidden=NO;
                }
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            

            if (relate) {
                if (self.dataArray.count>=1) {
                    if (relate.hidden==YES) {
                        self.tableView.frame=CGRectMake(0, 0, kScreenWidth, self.tableView.frame.size.height);
                    }
                    else
                    {
                        self.tableView.frame=CGRectMake(0, 0, kScreenWidth, kScreenHeight-64-45);
                        relate.hidden=YES;
                    }
                }
            }
            [self skipTableviewBottom];
        });
    });
    keyboardController.messageInputView.hidden=NO;

}
//刷新页面，并跳转到最后一行
- (void)skipTableviewBottom
{
    [self.tableView reloadData];
    if (self.dataArray.count > 0) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataArray.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
}
- (void)viewWillAppear:(BOOL)animated
{
    [[LCStatusBarOverlay shared] hidenMessageLabel];
    [self initializeData];
    [self app];
    [self.dataArray removeAllObjects];
    
    dispatch_queue_t queue = dispatch_get_main_queue();
    dispatch_async(queue, ^{
        if (self.isFromwhere==kWCEnterIntoConsultChatPeer) {
            self.dataArray=[ChatContent readItemFromChatContentTable:0 count:40 withUid:self.touid];
            
        }else if(self.isFromwhere==kWCEnterIntoConsultChatNoPeer)
        {
            self.dataArray=[ChatContent readItemFromChatContentTable:0 count:40 withQid:self.qid];
        }
        if (self.dataArray.count>=1) {
            relate.hidden=YES;
        }
        
        [self.tableView reloadData];
        if (self.dataArray.count > 0) {
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataArray.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
        }
        if (self.isFromwhere==0) {
        }
        else
        {
            if (self.isFromConsult) {
            }
            else
            {
                [self loadMyConsultQuestionInfo];
            }
        }
    });
    
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    voicetag=-1;
    pagecount=2;
    isSecondClick=NO;
    page = 0;
    Views=[[NSMutableArray alloc]init];
    self.reportArray = [[NSMutableArray alloc] init];
    UIBarButtonItem *backImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backClicked)];
    backImg.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backImg;
    
    self.dataArray=[[NSMutableArray alloc]init];
    self.tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-64-45) style:UITableViewStylePlain];
    self.tableView.dataSource=self;
    self.tableView.delegate=self;
    [self.tableView addHeaderWithTarget:self action:@selector(doloadMoreMessage)];
    self.tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor=[ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    [self.view addSubview:self.tableView];
    self.view.backgroundColor=[ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    imageArray=[[NSMutableArray alloc]init];
    
    if (kScreenWidth==414) {
        self.questionView=[[[NSBundle mainBundle]loadNibNamed:@"ConsultQuestionView" owner:self options:nil] lastObject];
    }else{
        self.questionView=[[[NSBundle mainBundle]loadNibNamed:@"ConsultQuestionView" owner:self options:nil] firstObject];
    }
    if (self.isFromwhere==kWCEnterIntoConsultChatPeer) {
        if (self.isFromReport) {
            UIButton *finishButton=[UIButton buttonWithType:UIButtonTypeCustom];
                finishButton.frame=CGRectMake(0, 0, 40, 30);
            [finishButton setTitle:@"完成" forState:UIControlStateNormal];
            [finishButton addTarget:self action:@selector(doneButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            finishButton.titleLabel.font=[UIFont systemFontOfSize:15];
            self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:finishButton];
            [self.tableView setEditing:YES];
        }
    }else if(self.isFromwhere==kWCEnterIntoConsultChatNoPeer)
    {
        if (self.isFromReport) {
            UIButton *finishButton=[UIButton buttonWithType:UIButtonTypeCustom];
            finishButton.frame=CGRectMake(0, 0, 40, 30);
            [finishButton setTitle:@"完成" forState:UIControlStateNormal];
            [finishButton addTarget:self action:@selector(doneButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            finishButton.titleLabel.font=[UIFont systemFontOfSize:15];

            self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:finishButton];
            [self.tableView setEditing:YES];
        }else
        {
            rightBtn =[[UIButton alloc]init];
            [rightBtn setTitle:@"结束咨询" forState:UIControlStateNormal];
            rightBtn.titleLabel.font=[UIFont systemFontOfSize:15];
            rightBtn.frame= CGRectMake(0, 0, 60, 30);
            [rightBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
            [rightBtn addTarget:self action:@selector(selectOver:) forControlEvents:UIControlEventTouchUpInside];
            
            self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
            
            self.overView=[[[NSBundle mainBundle]loadNibNamed:@"OverView" owner:self options:nil] lastObject];
            self.overView.overDelegate=self;
            self.overView.frame=CGRectMake(0, kScreenHeight, kScreenWidth, 44);
        }
    }
    if (self.isFromwhere==0) {
    }
    else
    {
        if (self.isFromConsult) {
            [self showQuestionInfoFromLocal:self.ConsultDic];
        }
        else
        {
        }
    }
    keyboardController = [QinKeyBoardController instance];
    keyboardController.viewController = self;
    keyboardController.messageDelegate=self;
    keyboardController.sendAudioView.voiceDelegate=self;
    keyboardController.sendPhotoView.photoDelegate=self;
    if (self.isFromwhere==kWCEnterIntoConsultChatPeer) {
        if (self.isFromReport) {
            isEdit=YES;
            keyboardController.messageInputView.hidden=YES;
        }else
        {
            keyboardController.messageInputView.hidden=NO;
        }
        self.navigationItem.title=self.userName;

    }else
    {
        if (self.isFromReport) {
            isEdit=YES;
            keyboardController.messageInputView.hidden=YES;
        }else
        {
            keyboardController.messageInputView.hidden=YES;
        }
        
        if ([self.consultType isEqualToString:@"1"]) {
            keyboardController.messageInputView.hidden=NO;

        }
        
        if (self.userName.length<=0) {
            self.navigationItem.title=@"咨询";
        }
        else
        {
            self.navigationItem.title=self.userName;
        }
    }
    [self.view addSubview:self.overView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doShowKeyboard) name:@"keyboard" object:nil];
}
- (void)doShowKeyboard
{
    [UIView animateWithDuration:0.2 animations:^{
        self.tableView.frame =CGRectMake(self.tableView.left, self.tableView.top, kScreenWidth, self.keyboardController.messageInputView.top);
        if (self.dataArray.count > 0) {
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataArray.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
        }
    }];
}
#pragma mark 请求我的问题详情
- (void)loadMyConsultQuestionInfo
{
    dispatch_queue_t queue = dispatch_get_main_queue();
    dispatch_async(queue, ^{
        NSString * getURL = [NSString stringWithFormat:@"%@question/patientdetail/?platform=%@&version=%@&qid=%@&people=1",kBaseURL,kPlatform,kVersion,self.qid];
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        [manager GET:getURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            MyNSLog("%@", responseObject);
            NSString *status=[NSString stringWithFormat:@"%@",[responseObject valueForKey:@"status"]];
            if ([status isEqualToString:@"1"]) {
                
                NSDictionary *quesInfo=[responseObject valueForKey:@"data"];
                
                //是否转诊
                NSString *isreferral=[NSString stringWithFormat:@"%@",[quesInfo valueForKey:@"isreferral"]];
                //初始指定状态
                NSString *initassign=[NSString stringWithFormat:@"%@",[quesInfo valueForKey:@"initassign"]];
                NSString *doctoruid=[NSString stringWithFormat:@"%@",[quesInfo valueForKey:@"doctoruid"]];
                if ([isreferral isEqualToString:@"1"]&&[initassign isEqualToString:@"1"]&&([doctoruid integerValue]>0)) {
                    
                    if ([ChatContent insertFirstIndex:quesInfo]) {
                        UserModel * userModel = [[UserManager shareInstance]getUserInfo];
                        //    NSString * name= userModel.username;
                        NSString *myuid=userModel.uid;

                        NSDictionary *dicMess = [[NSDictionary alloc] initWithObjectsAndKeys:@"send", @"action", myuid, @"myuid",self.toTpye, @"type", self.touid, @"uid", [NSString stringWithFormat:@"该问题已被转至%@医生为您解答！",[quesInfo valueForKey:@"doctorname"]], @"message", self.qid, @"qid", self.toMed, @"method", @"", @"pic", @"", @"voice",@"1" ,@"messageType",@"", @"voicelength",@"",@"voiceData", isreferral,@"isreferral",nil];
                        ChatContent *chat=[[ChatContent alloc]initWithDictionary:dicMess];
                        [self.dataArray insertObject:chat atIndex:0];
                        [self.tableView reloadData];
                    }
                }
                
                
                [self showQuestionInfo:quesInfo];
                NSString *uid=[NSString stringWithFormat:@"%@",[quesInfo valueForKey:@"doctoruid"]];
                if ([uid isEqualToString:@"0"]) {
                    self.navigationItem.title=@"咨询";
                }else
                {
                    self.navigationItem.title=[quesInfo valueForKey:@"doctorname"];
                    [ConsultList refreshTheDepartment:[quesInfo valueForKey:@"departmentname"] AndDoctor:[quesInfo valueForKey:@"doctorname"] andQid:self.qid];
                    self.userName=[quesInfo valueForKey:@"doctorname"];
                }
            }
            {
                [self.tableView reloadData];
                
                if (self.dataArray.count > 0) {
                    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataArray.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
                }
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            MyNSLog("%@", operation.responseString);
        }];
    });
}
/**
 *  咨询的问题展示
 */
- (void)showQuestionInfo:(NSDictionary *)quesInfo
{
    self.tableView.frame=CGRectMake(0, 0, kScreenWidth, kScreenHeight-64);
    [self.questionView.docImage setImageURL:[NSURL URLWithString:[quesInfo valueForKey:@"docavatar"]] placeholder:[UIImage imageNamed:@"默认头像.png"]];
    NSString *follow=[NSString stringWithFormat:@"%@",[quesInfo valueForKey:@"follow"]];
    if ([follow isEqualToString:@"0"]) {
        [self.questionView.attention setTitle:@"关注" forState:UIControlStateNormal];
        [self.questionView.attention addTarget:self action:@selector(doDocAttention:) forControlEvents:UIControlEventTouchUpInside];
    }else if([follow isEqualToString:@"1"])
    {
        [self.questionView.attention setTitle:@"已关注" forState:UIControlStateNormal];
        [self.questionView.attention addTarget:self action:@selector(doDocAttention:) forControlEvents:UIControlEventTouchUpInside];
    }
    else{
        self.questionView.attention.hidden=YES;
    }
    
    if ([[quesInfo valueForKey:@"departmentname"] length]<=0) {
        self.questionView.department.text=@"不确定科室";
    }
    else
    {
        self.questionView.department.text=[quesInfo valueForKey:@"departmentname"];
    }
    [self autosizeFontAndSize:self.questionView.department withText:self.questionView.department.text];
    
    if ([[NSString stringWithFormat:@"%@",[quesInfo valueForKey:@"doctorname"]] length]>0) {
        self.questionView.doctor.text=[NSString stringWithFormat:@"%@",[quesInfo valueForKey:@"doctorname"]];
        self.questionView.docName.text=[NSString stringWithFormat:@"%@",[quesInfo valueForKey:@"doctorname"]];
        self.touid=[NSString stringWithFormat:@"%@",[quesInfo valueForKey:@"doctoruid"]];
        [self autosizeFontAndSize:self.questionView.doctor withText:self.questionView.doctor.text];
    }else
    {
        self.questionView.doctor.text=@"";
    }
    
    self.doctorid=[NSString stringWithFormat:@"%@",[quesInfo valueForKey:@"doctorid"]];
    self.doctoruid=[NSString stringWithFormat:@"%@",[quesInfo valueForKey:@"doctoruid"]];
    self.userName=[quesInfo valueForKey:@"doctorname"];
    
    //判断是指定还是未指定
    if (![[NSString stringWithFormat:@"%@",[quesInfo valueForKey:@"doctoruid"]] isEqualToString:@"0"]) {
        self.questionView.doctorV.hidden=NO;
        
        self.questionView.doctorV.frame=CGRectMake(self.questionView.doctorV.left, self.questionView.doctorV.top, kScreenWidth,IPhone6Plus?64:54);
        self.questionView.questionDescription.frame=CGRectMake(kScreenWidth==414?20:15, 59, self.questionView.questionDescription.width, self.questionView.questionDescription.height);
        
    }else
    {
        self.questionView.doctorV.hidden=YES;
        self.questionView.doctor.text=@"";
        self.questionView.docName.text=@"";
        self.questionView.partLine.hidden=YES;
        self.questionView.questionDescription.frame=CGRectMake(kScreenWidth==414?20:15, 0, self.questionView.questionDescription.width, self.questionView.questionDescription.height);
        
    }

    self.questionView.questionDescription.text=[quesInfo valueForKey:@"message"];
    self.questionMessage=[quesInfo valueForKey:@"message"];
    self.questionView.time.text=[quesInfo valueForKey:@"date"];
    [self autosizeFontAndSize:self.questionView.time withText:self.questionView.time.text];
    [self autosizeFontAndSize:self.questionView.questionDescription withText:self.questionView.questionDescription.text];
    /**
     *  调整视图frame
     */
    self.questionView.partLine.frame=CGRectMake(self.questionView.department.right+5, self.questionView.partLine.top+1, self.questionView.partLine.width, self.questionView.partLine.height);
    self.questionView.doctor.frame=CGRectMake(self.questionView.partLine.right+5, self.questionView.doctor.top, self.questionView.doctor.width, self.questionView.doctor.height);
    self.questionView.consultType.frame=CGRectMake(self.questionView.doctor.right+15, self.questionView.consultType.top, self.questionView.consultType.width, self.questionView.consultType.height);
    
    self.questionView.time.frame=CGRectMake(kScreenWidth-15-self.questionView.time.width, self.questionView.time.top,self.questionView.time.width,self.questionView.time.height);
    self.questionView.clock.frame=CGRectMake(self.questionView.time.left-5-self.questionView.clock.width, self.questionView.clock.top, self.questionView.clock.width, self.questionView.clock.height);


    self.questionView.questionDescription.frame=CGRectMake(kScreenWidth==414?20:15, 59, self.questionView.questionDescription.size.width, self.questionView.questionDescription.size.height);

    
    if ([self.consultType isEqualToString:@"1"]) {
        self.questionView.consultType.text=@"视频咨询";
        self.questionView.consultType.backgroundColor=[ClassMethodsViewController colorWithHexString:@"#ff9d9d"];
    }else if ([self.consultType isEqualToString:@"0"])
    {
        self.questionView.consultType.text=@"图文咨询";
        self.questionView.consultType.backgroundColor=[ClassMethodsViewController colorWithHexString:@"#4fc1e9"];
    }
    
    if ([[quesInfo valueForKey:@"pic"] count]>0) {
        for (int i=0; i<[[quesInfo valueForKey:@"pic"] count]; i++) {
            UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(15+i*(55+(kScreenWidth-55*4-30)/3), self.questionView.questionDescription.bottom+10, 55, 55)];
            NSArray *arr=[[[quesInfo valueForKey:@"pic"] objectAtIndex:i] componentsSeparatedByString:@"@"];
            [imageView setImageURL:[NSURL URLWithString:[arr objectAtIndex:0]] placeholder:[UIImage imageNamed:@"公用_默认图片"]];
            imageView.layer.cornerRadius=2;
            imageView.userInteractionEnabled=YES;

            UITapGestureRecognizer *tapImage=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapQuestionImage:)];
            [imageView addGestureRecognizer:tapImage];
            [Views addObject:imageView];
            [imageArray addObject:[[quesInfo valueForKey:@"pic"] objectAtIndex:i]];
            imageView.layer.masksToBounds=YES;
            imageView.tag=3000+i;
            [self.questionView.question addSubview:imageView];
        }
        
        if (![self.doctoruid isEqualToString:@"0"]) {
            self.questionView.question.frame=CGRectMake(self.questionView.question.left, self.questionView.question.top, kScreenWidth, self.questionView.questionDescription.bottom+10+55+10);
        }
        else
        {
            self.questionView.question.frame=CGRectMake(self.questionView.question.left, 10, kScreenWidth, self.questionView.questionDescription.bottom+10+55+10);
        }
    }
    else
    {
        if (![self.doctoruid isEqualToString:@"0"]) {
            self.questionView.question.frame=CGRectMake(self.questionView.question.left, self.questionView.question.top<=10?self.questionView.question.top+10+(IPhone6Plus?64:54):self.questionView.question.top, kScreenWidth, self.questionView.questionDescription.bottom+10+10);
        }
        else
        {
            self.questionView.question.frame=CGRectMake(self.questionView.question.left, 10, kScreenWidth, self.questionView.questionDescription.bottom+10+10);
        }
    }
    self.questionView.frame=CGRectMake(self.questionView.left, self.questionView.top, kScreenWidth, self.questionView.question.bottom);
    self.tableView.tableHeaderView=self.questionView;
    
    if ([[quesInfo valueForKey:@"docdateline"] integerValue]<=0||[[NSString stringWithFormat:@"%@",[quesInfo valueForKey:@"over"]] isEqualToString:@"1"]) {
        keyboardController.messageInputView.hidden=YES;
        if ([[NSString stringWithFormat:@"%@",[quesInfo valueForKey:@"over"]] isEqualToString:@"1"]) {
            self.selfOver=@"1";
            if ([[NSString stringWithFormat:@"%@",[quesInfo valueForKey:@"doctoruid"]] isEqualToString:@"0"])
            {
                rightBtn.hidden=YES;
            }
            else
            {
                [rightBtn setTitle:@"评价" forState:UIControlStateNormal];
            }
            if ([[NSString stringWithFormat:@"%@",[quesInfo valueForKey:@"good"]] isEqualToString:@"0"]) {
                self.tableView.frame=CGRectMake(0, 0, kScreenWidth, kScreenHeight-64-45);
                [UIView animateWithDuration:0.2 animations:^{
                    self.overView.frame=CGRectMake(0, kScreenHeight-64-44, kScreenWidth, 44);
                }];
            }else
            {
                self.tableView.frame=CGRectMake(0, 0, kScreenWidth, kScreenHeight-64);
            }

        }
    }else
    {
        self.selfOver=@"0";
        keyboardController.messageInputView.hidden=NO;
        self.overView.hidden=YES;
        [rightBtn setTitle:@"结束咨询" forState:UIControlStateNormal];
        self.tableView.frame=CGRectMake(0, 0, kScreenWidth, kScreenHeight-64-45);
    }
    

    if (kScreenWidth==414) {
        if (!relate) {
            relate=[[[NSBundle mainBundle]loadNibNamed:@"RelatedIssuesView" owner:self options:nil] lastObject];
        }
        
    }else{
        if (!relate) {
            relate=[[[NSBundle mainBundle]loadNibNamed:@"RelatedIssuesView" owner:self options:nil] objectAtIndex:0];
        }
    }
    
    [relate reloadMytableview:[quesInfo valueForKey:@"relation"] WithKeywords:[quesInfo valueForKey:@"hight_keywords"]];
    relate.relatedDelegate=self;
    //指定（不显示推送医生个数，即不展示RelatedIssuesView.tabelview 的headerview）；
    if ([[NSString stringWithFormat:@"%@",[quesInfo valueForKey:@"doctorid"]] length]>3) {
        
        RelatedHeaderVeiw *relatedhead;
        if (kScreenWidth==414) {
            relatedhead=[[[NSBundle mainBundle]loadNibNamed:@"RelatedHeaderView" owner:self options:nil] lastObject];
        }else{
            relatedhead=[[[NSBundle mainBundle]loadNibNamed:@"RelatedHeaderView" owner:self options:nil] objectAtIndex:0];
        }
        //是否转诊
        NSString *isreferral=[NSString stringWithFormat:@"%@",[quesInfo valueForKey:@"isreferral"]];
        //初始指定状态
        NSString *initassign=[NSString stringWithFormat:@"%@",[quesInfo valueForKey:@"initassign"]];
        if ([isreferral isEqualToString:@"0"]&&[initassign isEqualToString:@"1"]) {
            relatedhead.content.text=@"您所指定的医生暂时无法回复您的咨询问题，请耐心等待。24小时内若无回复，则该问题将会转诊至其他医生为您解答！";
            [self autosizeFontAndSize:relatedhead.content withText:relatedhead.content.text];
        }
        else if ([isreferral isEqualToString:@"1"]&&[initassign isEqualToString:@"1"])
        {
            //指定过其他医生，并且转诊了，医生抢答了
        }
        relatedhead.frame=CGRectMake(relatedhead.left, relatedhead.top, kScreenWidth, relatedhead.content.height+2*(IPhone6Plus?15:10));
        relate.tableview.tableHeaderView=relatedhead;

        
        
    }
    //未指定（显示推送医生个数）
    else
    {
        RelatedHeaderVeiw *relatedhead;
        if (kScreenWidth==414) {
            relatedhead=[[[NSBundle mainBundle]loadNibNamed:@"RelatedHeaderView" owner:self options:nil] lastObject];
        }else{
            relatedhead=[[[NSBundle mainBundle]loadNibNamed:@"RelatedHeaderView" owner:self options:nil] objectAtIndex:0];
        }
        //是否转诊
        NSString *isreferral=[NSString stringWithFormat:@"%@",[quesInfo valueForKey:@"isreferral"]];
        //初始指定状态
        NSString *initassign=[NSString stringWithFormat:@"%@",[quesInfo valueForKey:@"initassign"]];
        if ([isreferral isEqualToString:@"1"]&&[initassign isEqualToString:@"1"]) {
            relatedhead.content.text=@"您的问题已被转诊，请耐心等待回复";
        }else
        {
            NSString *showStr=[NSString stringWithFormat:@"您的问题已提交给%@位医生，请等待回复!",[quesInfo valueForKey:@"doctor_count"]];
            NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:showStr];
            NSRange range=[showStr rangeOfString:[NSString stringWithFormat:@"%@",[quesInfo valueForKey:@"doctor_count"]]];
            [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:25] range:range];
            relatedhead.content.attributedText=attributedString;
        }
        relatedhead.frame=CGRectMake(relatedhead.left, relatedhead.top, kScreenWidth, relatedhead.content.height+2*(IPhone6Plus?15:10));
        relate.tableview.tableHeaderView=relatedhead;
    }
    if ([[quesInfo valueForKey:@"relation"] count]<=0) {
        //不展示“还没有医生回复，你可以先看看...”文字
        
    }else if ([[quesInfo valueForKey:@"relation"] count]<=4)
    {
    }else
    {
        //footterview
        RelatedFoottView *relatedfoot;
        if (kScreenWidth==414) {
            relatedfoot=[[[NSBundle mainBundle]loadNibNamed:@"RelatedFoottView" owner:self options:nil] lastObject];
        }else
        {
            relatedfoot=[[[NSBundle mainBundle]loadNibNamed:@"RelatedFoottView" owner:self options:nil] objectAtIndex:0];
        }
        relatedfoot.key=[quesInfo valueForKey:@"hight_keywords"];
        relatedfoot.relatedMoreDelegate=self;
        relate.tableview.tableFooterView=relatedfoot;
    }
    if ([[quesInfo valueForKey:@"pic"] count]>0) {
        
        if (kScreenHeight==480) {
            relate.frame = CGRectMake(0, relate.top, kScreenWidth, 264+40);
        }else
        {
            relate.frame = CGRectMake(0, relate.top, kScreenWidth,IPhone6Plus?358+40: 308+40);
        }
        
        
    }else
    {
        if (kScreenHeight==480)
        {
            relate.frame = CGRectMake(0, relate.top, kScreenWidth, 308+40);
        }
        else
        {
            relate.frame = CGRectMake(0, relate.top, kScreenWidth,IPhone6Plus?408+40: 352+40);
        }
        
    }
    
    self.tableView.contentSize=CGSizeMake(kScreenWidth, self.questionView.height+600);
    
    if (relate.hidden==NO) {
        if ([[quesInfo valueForKey:@"docdateline"] integerValue]==0) {
            relate.hidden=NO;
        }else
        {
            relate.hidden=YES;
        }
    }
    
    [self.tableView reloadData];
}
- (void)showQuestionInfoFromLocal:(NSDictionary *)quesInfo
{
    self.tableView.frame=CGRectMake(0, 0, kScreenWidth, kScreenHeight-64);

    if ([[quesInfo valueForKey:@"departmentname"] length]<=0) {
        self.questionView.department.text=@"不确定科室";
    }
    else
    {
        self.questionView.department.text=[quesInfo valueForKey:@"departmentname"];
    }
    [self autosizeFontAndSize:self.questionView.department withText:self.questionView.department.text];
    NSString *follow=[NSString stringWithFormat:@"%@",[quesInfo valueForKey:@"follow"]];

    if ([follow isEqualToString:@"0"]) {
        [self.questionView.attention setTitle:@"关注" forState:UIControlStateNormal];
        [self.questionView.attention addTarget:self action:@selector(doDocAttention:) forControlEvents:UIControlEventTouchUpInside];
    }else if([follow isEqualToString:@"1"])
    {
        [self.questionView.attention setTitle:@"已关注" forState:UIControlStateNormal];
        [self.questionView.attention addTarget:self action:@selector(doDocAttention:) forControlEvents:UIControlEventTouchUpInside];
    }
    else{
        self.questionView.attention.hidden=YES;
    }

    
    //判断是指定还是未指定
    if (self.isAssin) {
        [self.questionView.docImage setImageURL:[NSURL URLWithString:[quesInfo valueForKey:@"picurl"]] placeholder:[UIImage imageNamed:@"公用_默认头像.png"]];

        self.questionView.doctorV.hidden=NO;
        self.questionView.doctorV.frame=CGRectMake(self.questionView.doctorV.left, self.questionView.doctorV.top, kScreenWidth,IPhone6Plus?64:54);
        self.questionView.questionDescription.frame=CGRectMake(kScreenWidth==414?20:15, 59, self.questionView.questionDescription.width, self.questionView.questionDescription.height);
        //之前的
        self.questionView.doctor.text=[NSString stringWithFormat:@"%@",[quesInfo valueForKey:@"doctorname"]];
        self.questionView.docName.text=[NSString stringWithFormat:@"%@",[quesInfo valueForKey:@"doctorname"]];
        [self autosizeFontAndSize:self.questionView.doctor withText:self.questionView.doctor.text];
        self.doctorid=[quesInfo valueForKey:@"doctorid"];
        self.touid=[NSString stringWithFormat:@"%@",[quesInfo valueForKey:@"doctoruid"]];


    }
    else
    {
        
        self.questionView.doctorV.hidden=YES;
        self.questionView.questionDescription.frame=CGRectMake(kScreenWidth==414?20:15, 0, self.questionView.questionDescription.width, self.questionView.questionDescription.height);
        
       
        self.questionView.partLine.hidden=YES;
    }
    self.questionView.questionDescription.text=[quesInfo valueForKey:@"content"];
    self.questionMessage=[quesInfo valueForKey:@"content"];
    self.questionView.time.text=[quesInfo valueForKey:@"dateline"];
    [self autosizeFontAndSize:self.questionView.time withText:self.questionView.time.text];
    [self autosizeFontAndSize:self.questionView.questionDescription withText:self.questionView.questionDescription.text];
    /**
     *  调整视图frame
     */
    self.questionView.partLine.frame=CGRectMake(self.questionView.department.right+5, self.questionView.partLine.top+2, self.questionView.partLine.width, self.questionView.partLine.height);
    self.questionView.doctor.frame=CGRectMake(self.questionView.partLine.right+5, self.questionView.doctor.top, self.questionView.doctor.width, self.questionView.doctor.height);
    self.questionView.consultType.frame=CGRectMake(self.questionView.doctor.right+15, self.questionView.consultType.top, self.questionView.consultType.width, self.questionView.consultType.height);
    
    self.questionView.time.frame=CGRectMake(kScreenWidth-15-self.questionView.time.width, self.questionView.time.top,self.questionView.time.width,self.questionView.time.height);
    self.questionView.clock.frame=CGRectMake(self.questionView.time.left-5-self.questionView.clock.width, self.questionView.clock.top, self.questionView.clock.width, self.questionView.clock.height);
    
    
    self.questionView.questionDescription.frame=CGRectMake(kScreenWidth==414?20:15, 59, self.questionView.questionDescription.width, self.questionView.questionDescription.height);
    self.tableView.tableHeaderView=self.questionView;
    
    if ([self.consultType isEqualToString:@"1"]) {
        self.questionView.consultType.text=@"视频咨询";
        self.questionView.consultType.backgroundColor=[ClassMethodsViewController colorWithHexString:@"#ff9d9d"];
    }else if ([self.consultType isEqualToString:@"0"])
    {
        self.questionView.consultType.text=@"视频咨询";
        self.questionView.consultType.backgroundColor=[ClassMethodsViewController colorWithHexString:@"#4fc1e9"];
    }
    
    
    if ([[quesInfo valueForKey:@"pic"] length]>0) {
        NSArray *picArray=[[quesInfo valueForKey:@"pic"]componentsSeparatedByString:@","];
        for (int i=0; i<[picArray count]; i++) {
            UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(15+i*(55+(kScreenWidth-55*4-30)/3), self.questionView.questionDescription.bottom+10, 55, 55)];
            imageView.tag=3000+i;
            UITapGestureRecognizer *tapImage=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapQuestionImage:)];
            [imageView addGestureRecognizer:tapImage];
            imageView.userInteractionEnabled=YES;
            [imageArray addObject:[picArray objectAtIndex:i]];
            [Views addObject:imageView];
            [imageView setImageURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",KImgurl,[picArray objectAtIndex:i]]] placeholder:[UIImage imageNamed:@"公用_默认图片"]];
            [self.questionView.question addSubview:imageView];
        }
        if (self.isAssin) {
            self.questionView.question.frame=CGRectMake(self.questionView.question.left, self.questionView.question.top, kScreenWidth, self.questionView.questionDescription.bottom+10+55+10);
        }
        else
        {
            self.questionView.question.frame=CGRectMake(self.questionView.question.left, 10, kScreenWidth, self.questionView.questionDescription.bottom+10+55+10);
        }
    }
    else
    {
        if (self.isAssin) {
            self.questionView.question.frame=CGRectMake(self.questionView.question.left, self.questionView.question.top+0, kScreenWidth, self.questionView.questionDescription.bottom+10);
        }
        else
        {
            self.questionView.question.frame=CGRectMake(self.questionView.question.left, 10, kScreenWidth, self.questionView.questionDescription.bottom+10);
        }
        
    }
   self.questionView.frame=CGRectMake(self.questionView.left, self.questionView.top, kScreenWidth, self.questionView.question.bottom);
    self.tableView.tableHeaderView=self.questionView;
    self.doctorid=[quesInfo valueForKey:@"doctorid"];
    self.doctoruid=[quesInfo valueForKey:@"doctoruid"];
    keyboardController.messageInputView.hidden=YES;

    if ([self.consultType isEqualToString:@"0"]) {
        if (kScreenWidth==414) {
            relate=[[[NSBundle mainBundle]loadNibNamed:@"RelatedIssuesView" owner:self options:nil]lastObject];
        }
        else{
            relate=[[[NSBundle mainBundle]loadNibNamed:@"RelatedIssuesView" owner:self options:nil] objectAtIndex:0];
        }
        [relate reloadMytableview:[quesInfo valueForKey:@"relation"] WithKeywords:[quesInfo valueForKey:@"hight_keywords"]];
        relate.relatedDelegate=self;
        //指定（不显示推送医生个数，即不展示RelatedIssuesView.tabelview 的headerview）；
        if (self.isAssin) {
        }
        //未指定（显示推送医生个数）
        else
        {
            RelatedHeaderVeiw *relatedhead;
            
            if (kScreenWidth==414) {
                relatedhead=[[[NSBundle mainBundle]loadNibNamed:@"RelatedHeaderView" owner:self options:nil] lastObject];
            }
            else{
                relatedhead=[[[NSBundle mainBundle]loadNibNamed:@"RelatedHeaderView" owner:self options:nil] objectAtIndex:0];
            }
            NSString *showStr=[NSString stringWithFormat:@"您的问题已提交给%@位医生，请等待回复!",[quesInfo valueForKey:@"doctor_count"]];
            NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:showStr];
            NSRange range=[showStr rangeOfString:[NSString stringWithFormat:@"%@",[quesInfo valueForKey:@"doctor_count"]]];
            [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:kScreenWidth==414?27:25] range:range];
            relatedhead.content.attributedText=attributedString;
            relate.tableview.tableHeaderView=relatedhead;
        }
        if ([[quesInfo valueForKey:@"relation"] count]<=0) {
            //不展示“还没有医生回复，你可以先看看...”文字
            
        }else if ([[quesInfo valueForKey:@"relation"] count]<=4)
        {
        }else
        {
            //footterview
            RelatedFoottView *relatedfoot;
            if (kScreenWidth==414) {
                relatedfoot=[[[NSBundle mainBundle]loadNibNamed:@"RelatedFoottView" owner:self options:nil] lastObject];
            }else{
                relatedfoot=[[[NSBundle mainBundle]loadNibNamed:@"RelatedFoottView" owner:self options:nil] objectAtIndex:0];
            }
            relatedfoot.key=[quesInfo valueForKey:@"hight_keywords"];
            relatedfoot.relatedMoreDelegate=self;
            relate.tableview.tableFooterView=relatedfoot;
        }
        if ([[[quesInfo valueForKey:@"pic"] componentsSeparatedByString:@","] count]>0) {
            if (kScreenHeight==480) {
                relate.frame = CGRectMake(0, relate.top, kScreenWidth, 264);
            }else
            {
                relate.frame = CGRectMake(0, relate.top, kScreenWidth,IPhone6Plus?358: 308);
            }
        }else
        {
            if (kScreenHeight==480) {
                relate.frame = CGRectMake(0, relate.top, kScreenWidth, 308);
                
            }
            else{
                relate.frame = CGRectMake(0, relate.top, kScreenWidth,IPhone6Plus?408: 352);
            }
        }

    }
}
- (void)clickmore:(NSString *)key
{
    RelatedListViewController *related=[[RelatedListViewController alloc]initWithNibName:@"RelatedListViewController" bundle:[NSBundle mainBundle]];
    related.keyword=key;
    [self.navigationController pushViewController:related animated:YES];
}
/**
 *  关注医生or取消关注
 *
 *  @param sender 当前的一医生
 */
- (void)doDocAttention:(UIButton *)sender
{
    [self showActionView];
    if ([sender.titleLabel.text isEqualToString:@"关注"]) {
        NSString * postURL = [NSString stringWithFormat:@"%@user/followdoctor/",kBaseURL];
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        NSDictionary *parameters = @{
                                     @"platform": kPlatform,
                                     @"version":kVersion,
                                     @"doctoruid":self.doctoruid,
                                     };
        [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
            [self hiddenActionView];
            NSString *status= [NSString stringWithFormat:@"%@",[responseObject valueForKey:@"status"]];
            if ([status isEqualToString:@"1"]) {
                [self.questionView.attention setTitle:@"已关注" forState:UIControlStateNormal];
                UIAlertView *pointAlert = [[UIAlertView alloc]initWithTitle:[NSString stringWithFormat:@"您已经成功关注了%@",self.userName]
                                                                    message:@"您可以在'我'-'我的医生'中查看所有关注."
                                                                   delegate:self
                                                          cancelButtonTitle:@"我知道了"
                                                          otherButtonTitles:nil, nil];
                [pointAlert show];
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [self hiddenActionView];
        }];
        
    }else if ([sender.titleLabel.text isEqualToString:@"已关注"])
    {
        
        NSString * postURL = [NSString stringWithFormat:@"%@user/unfollowdoctor/",kBaseURL];
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

        NSDictionary *parameters = @{
                                     @"platform": kPlatform,
                                     @"version":kVersion,
                                     @"doctoruid":self.doctoruid,
                                     };
        [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
            [self hiddenActionView];
            NSString *status= [NSString stringWithFormat:@"%@",[responseObject valueForKey:@"status"]];
            if ([status isEqualToString:@"1"]) {
                [self.questionView.attention setTitle:@"关注" forState:UIControlStateNormal];
                UIAlertView *pointAlert = [[UIAlertView alloc]initWithTitle:[NSString stringWithFormat:@"您已经成功取消关注%@",self.userName]
                                                                    message:nil
                                                                   delegate:self
                                                          cancelButtonTitle:@"我知道了"
                                                          otherButtonTitles:nil, nil];
                [pointAlert show];
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [self hiddenActionView];
        }];
    }
}
- (void)PopInfomation:(NSDictionary *)dic
{
    MyNSLog("%@",dic);
    MyNSLog("%@",self.qid);
    self.toMed = @"0";
    self.isFir = NO;
    if ([self.qid isEqualToString:[dic valueForKey:@"qid"]]) {
        [self sendMessage:[dic valueForKey:@"notifacation"]];
    }
}
#pragma mark - 播放语音
- (void)playVoice:(NSData *)data withIntiger:(NSInteger)tag
{
//    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
//    if ([[VideoManagerCenter instance] isOnlineChat]) {
//        [self showCustomHudSingleLine:@"视频通话中无法播放语音"];
//        return;
//    }
    [[AVAudioSession sharedInstance] setActive:YES error:nil];
    NSIndexPath *index=[NSIndexPath indexPathForRow:tag inSection:0];
    LCSendVoiceCell *cell=(LCSendVoiceCell *)[self.tableView cellForRowAtIndexPath:index];
    
    if (voicetag == -1) {
        isSecondClick=YES;
    } else {
        if (voicetag==tag&&isSecondClick&&([self.avPlay isPlaying]||[self.avPlay2 isPlaying])) {
            [self.avPlay stop];
            [self.avPlay2 stop];
            isSecondClick=YES;
            [[AVAudioSession sharedInstance] setActive:NO error:nil];
            return;
        }
        NSIndexPath *index2=[NSIndexPath indexPathForRow:voicetag inSection:0];
        LCSendVoiceCell *cell2=(LCSendVoiceCell *)[self.tableView cellForRowAtIndexPath:index2];
        [cell2.voiceImage stopAnimating];
        isSecondClick=YES;

    }
    //
    ChatContent *messageModel = [self.dataArray objectAtIndex:tag];
    NSInteger type = [messageModel.messageType integerValue];
    NSInteger messageDirect = [messageModel.messageDirection integerValue];
    if ([self.avPlay isPlaying]) {
        [self.avPlay stop];
        [cell.voiceImage stopAnimating];
    }
    if ([self.avPlay2 isPlaying]) {
        [self.avPlay2 stop];
        [cell.voiceImage stopAnimating];
    }
    if (type==kWCMessageTypeVoice) {
        if (messageDirect==kWCMessageDirectionOut) {
            AVAudioPlayer *player=[[AVAudioPlayer alloc] initWithData:messageModel.voiceData error:nil];
            player.delegate=self;
            self.avPlay=player;
            [self.avPlay play];
            
            
            
            NSMutableArray *imageArray1=[[NSMutableArray alloc] init];
            for (int i=1; i<5; i++) {
                NSString *fileName=[NSString stringWithFormat:@"音频_发出%d",i];
                //                NSString *filePath=[[NSBundle mainBundle] pathForResource:fileName ofType:@"png"];
                
                [imageArray1 addObject:[UIImage imageNamed:fileName]];
            }
            [cell.voiceImage setAnimationImages:imageArray1];
            [cell.voiceImage setAnimationDuration:3];
            [cell.voiceImage setAnimationRepeatCount:0];
            [cell.voiceImage startAnimating];
        } else {
            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            dispatch_group_t group = dispatch_group_create();
            dispatch_group_async(group, queue, ^{
                NSURL *audioUrl = [NSURL URLWithString:messageModel.voice];
                NSData *audioData = [[NSData alloc]initWithContentsOfURL:audioUrl];
                AVAudioPlayer *player=[[AVAudioPlayer alloc]initWithData:audioData error:nil];
                self.avPlay2=player;
                player.delegate=self;
            });
            dispatch_group_notify(group, dispatch_get_main_queue(), ^{
                [self.avPlay2 play];
                
                NSMutableArray *imageArray2=[[NSMutableArray alloc] init];
                for (int i=1; i<5; i++) {
                    NSString *fileName=[NSString stringWithFormat:@"音频_接收%d",i];
                    [imageArray2 addObject:[UIImage imageNamed:fileName]];
                }
                [cell.voiceImage setAnimationImages:imageArray2];
                [cell.voiceImage setAnimationDuration:3];
                [cell.voiceImage setAnimationRepeatCount:0];
                [cell.voiceImage startAnimating];
            });
        }
        
    }
    voicetag = tag;
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    [player stop];
    player.delegate = nil;
    isSecondClick=YES;
    [[AVAudioSession sharedInstance] setActive:NO error:nil];

    [[NSNotificationCenter defaultCenter] postNotificationName:@"kill" object:nil userInfo:nil];
}
#pragma mark - tableView delegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
      ChatContent *chat = [self.dataArray objectAtIndex:indexPath.row];
    if([chat.messageType isEqualToString:@"1"] ) {
        
            if ([[NSString stringWithFormat:@"%@",chat.method] isEqualToString:@"6"]) {
                MethodViewCell *cell=(MethodViewCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
                CGFloat f=cell.content.bottom+10;
                return f;
            }
            else if ([chat.isreferral isEqualToString:@"1"])
            {
                return 60;
            }
            else if ([chat.messageDirection isEqualToString:@"1"]) {
                
                LCSendTextSelfCell *cell=(LCSendTextSelfCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
                CGFloat f=cell.backImageView.frame.size.height+20;
                return f;
            }
            else
            {
                LCSendTextCell *cell=(LCSendTextCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
                CGFloat f=cell.backImageView.frame.size.height+20;
                return f;
            }
        
//        }
    } else if ([chat.messageType isEqualToString:@"2"]) {
        float width = [chat.width floatValue];
        float height = [chat.heigth floatValue];
        
        int maxWidth = 180;
        int maxHeight = 200;
        if (width > height) {
            return (width < maxWidth ? height : (height *maxWidth/width)) + 20;
        } else if (width < height){
            return (height < maxHeight ? height : maxHeight) + 20;
        } else {
            return (width < maxWidth ? width : maxWidth) + 20;
        }
    }
    else return 60;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dataArray count];
}
- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    ChatContent *messageModel = [self.dataArray objectAtIndex:indexPath.row];
    NSInteger type = [messageModel.messageType integerValue];
    NSInteger messageDirect = [messageModel.messageDirection integerValue];
    NSString *method=[NSString stringWithFormat:@"%@",messageModel.method];
    NSString *isreferral=[NSString stringWithFormat:@"%@",messageModel.isreferral];
    if (type==kWCMessageTypeImage) {
        static NSString *indentifier=@"imagecell";
        LCSendImageCell *imagecell = (LCSendImageCell *)[tableView dequeueReusableCellWithIdentifier:indentifier];
        
        if (imagecell==nil) {
            imagecell=[[LCSendImageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentifier];
        }
        int maxWidth = 180;
        int maxHeight = 200;
        imagecell.delegate=self;
        imagecell.tag=indexPath.row;
        //自己发出的图片排版。
        if (messageDirect==kWCMessageDirectionOut) {
            imagecell.iconImageView.frame = CGRectMake(kScreenWidth - 15 - 40, 13,40,40);
            
            UIImage * userImage;
            BOOL isHaveUserImage = [[UserManager shareInstance]isHaveUserImage];
            if (isHaveUserImage == YES) {
                userImage= [[UserManager shareInstance]getUserImage];
            }
             else userImage=[UIImage imageNamed:@"默认头像"];
            imagecell.iconImageView.image=userImage;
            imagecell.iconImageView.userInteractionEnabled = YES;
            imagecell.iconImageView.layer.cornerRadius=3;
            imagecell.iconImageView.layer.masksToBounds=YES;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(me)];
            [imagecell.iconImageView addGestureRecognizer:tap];

            //背景气泡
            imagecell.contentImageViewBg.image=[[UIImage imageNamed:@"图片_发出"] stretchableImageWithLeftCapWidth:46 topCapHeight:40];
            
            imagecell.contentImageView.image =[UIImage imageWithData:messageModel.imageData];
//            imagecell.contentImageView.frame=CGRectMake(300-180-40, 10, 180, 200);
            
            //图片的宽和高
            float width = [messageModel.width floatValue];
            float height = [messageModel.heigth floatValue];
            
            
            if (width < height) {  //高图
                imagecell.contentImageView.frame=CGRectMake(kScreenWidth-20-44-8 - (height < maxHeight ? width : width * maxHeight / height), 14, height < maxHeight ? width : width * maxHeight / height, (height < maxHeight ? height : maxHeight));
                
                imagecell.contentImageViewBg.frame=CGRectMake(imagecell.contentImageView.left , imagecell.contentImageView.top , imagecell.contentImageView.frame.size.width , imagecell.contentImageView.frame.size.height);
                    } else if (width > height){  //宽图
                imagecell.contentImageView.frame=CGRectMake(kScreenWidth-20-44-8 - (width < maxWidth ? width: maxWidth), 14, width <= maxWidth ? width : maxWidth, width < maxWidth ? height : (height *maxWidth/width));
                
                imagecell.contentImageViewBg.frame=CGRectMake(imagecell.contentImageView.left , imagecell.contentImageView.top , imagecell.contentImageView.frame.size.width , imagecell.contentImageView.frame.size.height);
                
            } else {  //正方形图
                imagecell.contentImageView.frame=CGRectMake(kScreenWidth-20-44-8 - (width < maxWidth ? width: maxWidth), 14, width <= maxWidth ? width : maxWidth, width < maxWidth ? width : maxWidth);
                
                imagecell.contentImageViewBg.frame=CGRectMake(imagecell.contentImageView.left , imagecell.contentImageView.top , imagecell.contentImageView.frame.size.width , imagecell.contentImageView.frame.size.height);
                
            }

            
            //转换时间戳
//            [imagecell.timeBtn setTitle:[self formateDateFromDateline:messageModel.dateline] forState:UIControlStateNormal];
        }
        //聊天左侧（对方的图片信息）图片展示
        else
        {
            if (self.isFromwhere==0){
                [imagecell.iconImageView setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@%@",BaseMessageListIconHeadUrl , self.touid, BaseMessageListIconTailUrl]] placeholderImage:[UIImage imageNamed:@"公用_默认头像"]];
            }else{
                [imagecell.iconImageView setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@&size=big%@", BaseMessageListDocIconHeadUrl, self.touid, BaseMessageListIconTailUrl]] placeholderImage:[UIImage imageNamed:@"公用_默认头像"]];
            }
            imagecell.iconImageView.frame=CGRectMake(15, 13,40,40);
            imagecell.iconImageView.layer.cornerRadius=3;
            imagecell.iconImageView.layer.masksToBounds=YES;
            imagecell.contentImageViewBg.image=[[UIImage imageNamed:@"图片_接收"] stretchableImageWithLeftCapWidth:55 topCapHeight:31];
            imagecell.iconImageView.userInteractionEnabled = YES;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(you)];
            [imagecell.iconImageView addGestureRecognizer:tap];
            //图片的宽和高
            float w = [messageModel.width floatValue];
            float h = [messageModel.heigth floatValue];
            
            if (w < h) {  //高图
                imagecell.contentImageView.frame=CGRectMake(69, 13, h < maxHeight ? w : (w*maxHeight/h), h < maxHeight ? h : maxHeight);
                imagecell.contentImageViewBg.frame=CGRectMake(imagecell.contentImageView.left , imagecell.contentImageView.top , imagecell.contentImageView.frame.size.width , imagecell.contentImageView.frame.size.height );
                [imagecell.contentImageView setImageURLStr:messageModel.pic placeholder:nil];
                
            } else if (w > h){  //宽图
                imagecell.contentImageView.frame=CGRectMake(69, 13, w < maxWidth ? w : maxWidth, w < maxWidth ? h : (h * maxWidth / w));
                imagecell.contentImageViewBg.frame=CGRectMake(imagecell.contentImageView.left , imagecell.contentImageView.top, imagecell.contentImageView.frame.size.width , imagecell.contentImageView.frame.size.height );
                
                
                [imagecell.contentImageView setImageWithURL:[NSURL URLWithString:messageModel.pic] placeholderImage:nil];
            } else {
                imagecell.contentImageView.frame=CGRectMake(69, 13, w < maxWidth ? w : maxWidth, w < maxWidth ? w : maxWidth);
                imagecell.contentImageViewBg.frame=CGRectMake(imagecell.contentImageView.left , imagecell.contentImageView.top , imagecell.contentImageView.frame.size.width , imagecell.contentImageView.frame.size.height );
                [imagecell.contentImageView setImageWithURL:[NSURL URLWithString:messageModel.pic] placeholderImage:nil];
            }
            //转换时间戳
        }
        cell=imagecell;
        
    }//展示文本
    else if(type==kWCMessageTypeText){
        
        if([method isEqualToString:@"6"])
        {
            static NSString *indenti=@"methodCell";
            MethodViewCell *methodcell=[tableView dequeueReusableCellWithIdentifier:indenti];
            if (!methodcell) {
                if (kScreenWidth==414) {
                    methodcell=[[[NSBundle mainBundle] loadNibNamed:@"MethodViewCell" owner:self options:nil] lastObject];
                }else{
                    methodcell=[[[NSBundle mainBundle] loadNibNamed:@"MethodViewCell" owner:self options:nil] firstObject];
                }
            }
            
            NSArray *info=[messageModel.message componentsSeparatedByString:@","];
            
            methodcell.content.text=[NSString stringWithFormat:@"发送挂号单\n预约医院：%@\n预约时间：%@\n挂号费用：%@",[info objectAtIndex:0],[info objectAtIndex:1],[info objectAtIndex:2]];
            methodcell.registeredId=[info objectAtIndex:3];
            methodcell.jiahaoDelegate=self;
            
            
            UserModel * userModel = [[UserManager shareInstance]getUserInfo];
            NSString *myuid=userModel.uid;
            NSUserDefaults *userDefault=[NSUserDefaults standardUserDefaults];
            if ([[userDefault valueForKey:[NSString stringWithFormat:@"%@%@",methodcell.registeredId,myuid]] isEqualToString:@"1"]) {
                methodcell.accept.userInteractionEnabled=NO;
                methodcell.reject.userInteractionEnabled=NO;
                [methodcell.accept setTitle:@"已接受" forState:UIControlStateNormal];

                methodcell.accept.backgroundColor=[ClassMethodsViewController colorWithHexString:@"#717171"];
                methodcell.reject.backgroundColor=[ClassMethodsViewController colorWithHexString:@"#717171"];
            }else if ([[userDefault valueForKey:[NSString stringWithFormat:@"%@%@",methodcell.registeredId,myuid]] isEqualToString:@"2"])
            {
                methodcell.accept.userInteractionEnabled=NO;
                methodcell.reject.userInteractionEnabled=NO;
                [methodcell.reject setTitle:@"已拒绝" forState:UIControlStateNormal];
                methodcell.accept.backgroundColor=[ClassMethodsViewController colorWithHexString:@"#717171"];
                methodcell.reject.backgroundColor=[ClassMethodsViewController colorWithHexString:@"#717171"];
            }
            methodcell.index=indexPath.row;
            CGSize size=[self autolayoutText:methodcell.content.text WithTextLabel:methodcell.content WithWidth:kScreenWidth==414?200:145];
            methodcell.content.frame=CGRectMake(kScreenWidth==414?20:15, 10,size.width, size.height);
            methodcell.accept.center=CGPointMake(methodcell.accept.center.x, methodcell.content.center.y);
            methodcell.reject.center=CGPointMake(methodcell.reject.center.x, methodcell.content.center.y);
            methodcell.bottomLine.frame=CGRectMake(0, methodcell.content.bottom+9.5, kScreenWidth, 0.5);
            cell=methodcell;
        }
        else if ([isreferral isEqualToString:@"1"])
        {
            static NSString *indentifierT=@"isreferral";
            UITableViewCell *referralcell=[tableView dequeueReusableCellWithIdentifier:indentifierT];
            if (!referralcell) {
                referralcell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentifierT];
            }
            referralcell.textLabel.font=[UIFont systemFontOfSize:LABEL_FONT_SIZE_CONTENT];
            referralcell.textLabel.text=messageModel.message;
            cell=referralcell;
        }
        else if (messageDirect==kWCMessageDirectionOut) {
            static NSString *indentifier=@"textcell2";
            LCSendTextSelfCell *textcell = [tableView dequeueReusableCellWithIdentifier:indentifier];
            if (!textcell) {
            textcell = [[[NSBundle mainBundle] loadNibNamed:@"LCSendTextSelfCell" owner:self options:nil] objectAtIndex:0];

            }
            textcell.contentLabel.userInteractionEnabled=YES;
            textcell.iconImageView.frame = CGRectMake(kScreenWidth - 15 - 40, 13, 40, 40);

            UIImage * userImage;
            BOOL isHaveUserImage = [[UserManager shareInstance]isHaveUserImage];
            if (isHaveUserImage == YES) {
                userImage= [[UserManager shareInstance]getUserImage];
            }
            else userImage=[UIImage imageNamed:@"默认头像"];
            textcell.iconImageView.image=userImage;
            textcell.iconImageView.userInteractionEnabled = YES;
            textcell.iconImageView.layer.cornerRadius=3;
            textcell.iconImageView.layer.masksToBounds=YES;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(me)];
            [textcell.iconImageView addGestureRecognizer:tap];

            while (1) {
                if ([[messageModel.message substringWithRange:NSMakeRange(0,1)] isEqualToString:@"\n"])
                    messageModel.message = [messageModel.message substringFromIndex:1];
                else
                    break;
            }
            textcell.contentLabel.text=messageModel.message;
            textcell.contentLabel.font=[UIFont systemFontOfSize:MESSAGE_TEXT_FONT];
//            [textcell cellforCoretext:messageModel.message];
            textcell.contentLabel.textColor=[UIColor clearColor];

//            [self autosizeFontAndSize:textcell.contentLabel withText:textcell.contentLabel.text];
            CGSize size=[self autolayoutText:messageModel.message WithTextLabel:textcell.contentLabel WithWidth:200];
            textcell.contentLabel.frame=CGRectMake(kScreenWidth-15-40-10-5-12-size.width,23, size.width+10, size.height);
            IFTweetLabel *tweetLabel = [[IFTweetLabel alloc] init];
            tweetLabel.userInteractionEnabled = YES;
            tweetLabel.backgroundColor=[UIColor clearColor];
            [tweetLabel setFont:[UIFont systemFontOfSize:MESSAGE_TEXT_FONT]];
            tweetLabel.tag=indexPath.row;
            [tweetLabel setTextColor:[UIColor whiteColor]];
            [tweetLabel setText:textcell.contentLabel.text];
            [tweetLabel setBackgroundColor:[UIColor clearColor]];
            [tweetLabel setNumberOfLines:0];
            UILongPressGestureRecognizer *longPress=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(dolongPress:)];
            [tweetLabel addGestureRecognizer:longPress];
//            [textcell addTarget];

            tweetLabel.ifTweetDelegate=self;
            if (size.height < 25) {
                tweetLabel.frame=CGRectMake(kScreenWidth-15-40-20-15-(size.width>190?190:size.width),22, size.width>190?200:size.width+10, size.height+2);
            }else
            {
                tweetLabel.frame=CGRectMake(kScreenWidth-15-40-10-5-12-200,22, 200, size.height+2);
            }
            [tweetLabel setLinksEnabled:YES];
            [textcell.contentView addSubview:tweetLabel];
            [tweetLabel sizeToFit];
            textcell.backImageView.image=[[UIImage imageNamed:@"聊天_发出"] stretchableImageWithLeftCapWidth:10 topCapHeight:30];
            if (size.height < 25) {
                textcell.backImageView.frame=CGRectMake(tweetLabel.left-7, 13, tweetLabel.width+14, 40);
            }else
            {
                textcell.backImageView.frame=CGRectMake(tweetLabel.left-6, 13, 215, size.height+2+4+14);
            }
            cell=textcell;
        }
        //对方的信息
        else{
            static NSString *indentifier=@"textcell";
            
            LCSendTextCell *textcell = (LCSendTextCell *)[tableView dequeueReusableCellWithIdentifier:indentifier];
            
            if (!textcell) {
                textcell = [[[NSBundle mainBundle] loadNibNamed:@"LCSendTextCell" owner:self options:nil] objectAtIndex:0];
            }
            textcell.iconImageView.userInteractionEnabled = YES;
            textcell.iconImageView.layer.cornerRadius=3;
            textcell.iconImageView.layer.masksToBounds=YES;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(you)];
            [textcell.iconImageView addGestureRecognizer:tap];
//            textcell.messageLabel.text = @"";
            if (self.isFromwhere==0){
                [textcell.iconImageView setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@%@",BaseMessageListIconHeadUrl , self.touid, BaseMessageListIconTailUrl]] placeholderImage:[UIImage imageNamed:@"公用_默认头像"]];
            }else{
                [textcell.iconImageView setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@&size=big%@", BaseMessageListDocIconHeadUrl, self.touid, BaseMessageListIconTailUrl]] placeholderImage:[UIImage imageNamed:@"公用_默认头像"]];
            }
            while (1) {
                if ([[messageModel.message substringWithRange:NSMakeRange(0,1)] isEqualToString:@"\n"])
                    messageModel.message = [messageModel.message substringFromIndex:1];
                else
                    break;
            }
            textcell.messageLabel.text=messageModel.message;
            textcell.messageLabel.font=[UIFont systemFontOfSize:MESSAGE_TEXT_FONT];

            CGSize size=[self autolayoutText:messageModel.message WithTextLabel:textcell.messageLabel WithWidth:200];
//            textcell.messageLabel.frame=CGRectMake(15+40+10+5+12,22, size.width+10, size.height);
//            [self autosizeFontAndSize:textcell.messageLabel withText:textcell.messageLabel.text];

            textcell.messageLabel.textColor=[UIColor clearColor];

            IFTweetLabel *tweetLabel = [[IFTweetLabel alloc] init];
            [tweetLabel setFont:[UIFont systemFontOfSize:MESSAGE_TEXT_FONT]];
            [tweetLabel setTextColor:[UIColor blackColor]];

            [tweetLabel setBackgroundColor:[UIColor clearColor]];
            [tweetLabel setNumberOfLines:0];
            UILongPressGestureRecognizer *longPress=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(dolongPress:)];
            [tweetLabel addGestureRecognizer:longPress];
            if (size.height < 25) {
                tweetLabel.frame=CGRectMake(85,23, size.width+10, size.height);
            }else
            {
                tweetLabel.frame=CGRectMake(85,23, 200, size.height);
            }
            [tweetLabel setText:textcell.messageLabel.text];
            [tweetLabel setLinksEnabled:YES];
            tweetLabel.ifTweetDelegate=self;
            tweetLabel.backgroundColor=[UIColor clearColor];
            [textcell.contentView addSubview:tweetLabel];
            [tweetLabel sizeToFit];
            if (size.height < 25) {
                textcell.backImageView.frame=CGRectMake(tweetLabel.left-14.5, 13, tweetLabel.width+15, 40);
            }
            else
            {
                textcell.backImageView.frame=CGRectMake(tweetLabel.left-14.5, 13, tweetLabel.width+23, tweetLabel.height+4+14+2);
            }
            textcell.backImageView.image=[[UIImage imageNamed:@"聊天_接收"] stretchableImageWithLeftCapWidth:15 topCapHeight:30];
             cell = textcell;
        }
    }
    //音频展示
    else{
        static NSString *indentifier=@"voiceCell";
        LCSendVoiceCell *voiceCell=[tableView dequeueReusableCellWithIdentifier:indentifier];
        if (voiceCell==nil) {
            voiceCell=[[LCSendVoiceCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentifier];
        }
        voiceCell.delegate=self;
        voiceCell.tag=indexPath.row;
        voiceCell.playButton.tag=indexPath.row;
        
        if (messageDirect== kWCMessageDirectionOut) {
            voiceCell.type_voice=kWCMessageDirectionOut;
            voiceCell.iconImageView.frame=CGRectMake(kScreenWidth - 15 -40, 13,40,40);
            
//            [voiceCell.iconImageView setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@%@", BaseMessageListIconHeadUrl, [[NSUserDefaults standardUserDefaults] objectForKey:@"SelfUidKey"], BaseMessageListIconTailUrl]] placeholderImage:[UIImage imageNamed:@"公用_默认头像"]];
            UIImage * userImage;
            BOOL isHaveUserImage = [[UserManager shareInstance]isHaveUserImage];
            if (isHaveUserImage == YES) {
                userImage= [[UserManager shareInstance]getUserImage];
            }
            else userImage=[UIImage imageNamed:@"默认头像"];
            voiceCell.iconImageView.image=userImage;
            voiceCell.iconImageView.layer.cornerRadius=3;
            voiceCell.iconImageView.layer.masksToBounds=YES;
            voiceCell.iconImageView.userInteractionEnabled = YES;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(me)];
            [voiceCell.iconImageView addGestureRecognizer:tap];

            voiceCell.backImage.image=[[UIImage imageNamed:@"聊天_发出"] stretchableImageWithLeftCapWidth:10 topCapHeight:30];
            
            voiceCell.timeLenth.text=[NSString stringWithFormat:@"%@\"",messageModel.voicelength];
            voiceCell.timeLenth.textColor=[UIColor whiteColor];
            voiceCell.timeLenth.font=[UIFont systemFontOfSize:LABEL_FONT_SIZE_CONTENT];

            voiceCell.backImage.frame = CGRectMake(kScreenWidth - 15 - 40 - 17 - 100, 13 , 100,40);
            voiceCell.playButton.frame = voiceCell.backImage.frame;
            voiceCell.timeLenth.frame = CGRectMake(voiceCell.backImage.left + 25, voiceCell.backImage.top + 12, 30, 15);
            voiceCell.voiceImage.frame=CGRectMake(voiceCell.backImage.right - 40, voiceCell.backImage.top +6.5, 14, 29);
            
            voiceCell.voiceImage.image=[UIImage imageNamed:@"音频_发出1.png"];
            
            //转换时间戳
//            [voiceCell.timeBtn setTitle:[self formateDateFromDateline:messageModel.dateline] forState:UIControlStateNormal];
        } else {
            voiceCell.type_voice=kWCMessageDirectionIn;
            voiceCell.iconImageView.frame=CGRectMake(15, 13,40,40);
            if (self.isFromwhere==0) {

                [voiceCell.iconImageView setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@%@", BaseMessageListIconHeadUrl, self.touid, BaseMessageListIconTailUrl]] placeholderImage:[UIImage imageNamed:@"公用_默认头像"]];
            }else{
                [voiceCell.iconImageView setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@&size=big%@", BaseMessageListDocIconHeadUrl, self.touid, BaseMessageListIconTailUrl]] placeholderImage:[UIImage imageNamed:@"公用_默认头像"]];
            }
            voiceCell.backImage.image=[[UIImage imageNamed:@"聊天_接收"] stretchableImageWithLeftCapWidth:15 topCapHeight:30];
            voiceCell.iconImageView.userInteractionEnabled = YES;
            voiceCell.iconImageView.layer.cornerRadius=3;
            voiceCell.iconImageView.layer.masksToBounds=YES;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(you)];
            [voiceCell.iconImageView addGestureRecognizer:tap];
            
            MyNSLog("%@",messageModel.voicelength);
            voiceCell.timeLenth.text=[NSString stringWithFormat:@"%@\"",messageModel.voicelength];
            voiceCell.timeLenth.textColor=[UIColor blackColor];
            voiceCell.timeLenth.font=[UIFont systemFontOfSize:LABEL_FONT_SIZE_CONTENT];
            voiceCell.backImage.frame = CGRectMake(70,13, 100,40);
            voiceCell.playButton.frame = voiceCell.backImage.frame;
            voiceCell.timeLenth.frame = CGRectMake(voiceCell.backImage.right - 39, voiceCell.backImage.top + 12, 30, 15);
            voiceCell.voiceImage.frame = CGRectMake(voiceCell.backImage.left + 26, voiceCell.backImage.top + 6, 14, 29);
            //灰色
            voiceCell.voiceImage.image=[UIImage imageNamed:@"音频_接收1.png"];
            
            //转换时间戳
//            [voiceCell.timeBtn setTitle:[self formateDateFromDateline:messageModel.dateline] forState:UIControlStateNormal];
        }
        cell=voiceCell;
    }
    
    if (self.isFromReport) {
        cell.selectionStyle = UITableViewCellSelectionStyleDefault;
        UIView *selectedView = [[UIView alloc] initWithFrame:cell.frame];
//        selectedView.backgroundColor = [self colorWithHexString:@"#ecf4f6"];
        cell.selectedBackgroundView = selectedView;
    } else {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}

- (void)setEditing:(BOOL)editing animated:(BOOL)animated

{
    
    [super setEditing:editing animated:animated];
    [self.tableView setEditing:editing animated:animated];
    
}
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleInsert | UITableViewCellEditingStyleDelete;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.inputToolBarView.textView resignFirstResponder];
    
    if (isEdit) {
        @try {
            [self.reportArray addObject:[self.dataArray objectAtIndex:indexPath.row]];
        }
        @catch (NSException *exception) {
            MyNSLog("exception = %@", exception);
        }
    }
    else
    {
        [keyboardController downMytableview];
    }
}
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (isEdit) {
        @try {
            [self.reportArray removeObject:[self.dataArray objectAtIndex:indexPath.row]];
        }
        @catch (NSException *exception) {
            MyNSLog("exception = %@", exception);
        }
    }
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    return;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (relate.hidden == NO) {
        return relate;
    }
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (relate.hidden == NO) {
        return relate.frame.size.height;
    }
    else
    {
//        keyboardController.messageInputView.h
        return 0.01;
    }
    
}
- (void)me
{
//    ReportViewController *report=[[ReportViewController alloc]initWithNibName:@"ReportViewController" bundle:[NSBundle mainBundle]];
//    [self.navigationController pushViewController:report animated:YES];
    FirendDetailViewController *personInfo=[[FirendDetailViewController alloc] initWithNibName:@"FirendDetailViewController" bundle:[NSBundle mainBundle]];
    UserModel * userModel = [[UserManager shareInstance]getUserInfo];
//    NSString * name= userModel.username;
    NSString *myuid=userModel.uid;
    personInfo.firendId=myuid;
    [self.navigationController pushViewController:personInfo animated:YES];
}
- (void)you
{
    if(self.isFromwhere==0){
        FirendDetailViewController *friend=[[FirendDetailViewController alloc]initWithNibName:@"FirendDetailViewController" bundle:[NSBundle mainBundle]];
        friend.firendId=self.touid;
        [self.navigationController pushViewController:friend animated:YES];

    }else if(self.isFromwhere==1)
    {
        DocInfoViewController *doctor=[[DocInfoViewController alloc]initWithNibName:@"DocInfoViewController" bundle:[NSBundle mainBundle]];
        if (self.doctoruid.length>0) {
            doctor.doctoruid=self.doctoruid;
            [self.navigationController pushViewController:doctor animated:YES];

        }
    }
    
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma  mark imagePickerControllerDelegate
//- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
//    
////    UIImage * image = [info objectForKey:UIImagePickerControllerEditedImage];
//    [self loadData1:info];
//    [picker dismissViewControllerAnimated:YES completion:NULL];
//}
/**
 *  发送图片
 *
 *  @param dic 图片的信息
 */
- (void)loadData1:(UIImage *)image
{
    
    UIImage *postImage = image;
    NSData* imageData = UIImageJPEGRepresentation(postImage, 0.5);
    
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"%@message/uploadimage/",kBaseURL] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:imageData name:@"file" fileName:@"george.jpg" mimeType:@"image/jpeg"];
    } error:nil];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSProgress *progress = nil;
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            MyNSLog("Error: %@", error);
        } else {
            //图片上传成功
            NSString *status=[NSString stringWithFormat:@"%@",[responseObject valueForKey:@"status"]];
            if ([status isEqualToString:@"1"])
            {
                [self postPicFinished:[responseObject objectForKey:@"data"]];
                [self imageDataInserLocal:image];
                
                NSURL *url=[[NSURL alloc]initFileURLWithPath:[[NSBundle mainBundle] pathForResource:@"sendSuccess" ofType:@"caf"]];
                AVAudioPlayer *player=[[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
                self.sendPlay=player;
                [self.sendPlay play];
            }
            else
            {
            }
        }
    }];
    [uploadTask resume];
}
-(void)postPicFinished:(NSString *)url
{
    
    UserModel * userModel = [[UserManager shareInstance]getUserInfo];
    NSString *myuid=userModel.uid;
    
    NSDictionary *dictionary;
    if ([self.qid length] == 0){
        self.qid = @"0";
    }
    dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"send", @"action", myuid, @"from_uid", @"1", @"from_type",self.toTpye, @"to_type",self.touid, @"to_uid", @"", @"message", url, @"pic",self.qid,@"qid",@"0",@"method",@"", @"voice", @"", @"voicelength", nil];
    AppDelegate *del = (AppDelegate *)[UIApplication sharedApplication].delegate;
    NSString *jsonString = [dictionary JSONString];
    
    @try {
        if (del.webSocket.readyState == 1) {
            [del.webSocket send:jsonString];
        } else {
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"CONNECT_WEBSOCKDET" object:nil userInfo:nil];
            AppDelegate *app=(AppDelegate *)[[UIApplication sharedApplication]delegate];
            [app webSocket];
        }
    }
    @catch (NSException *exception) {
        MyNSLog("exception = %@", exception);
    }
}

-(void)imageDataInserLocal:(UIImage *)image
{
    UIImage *postImage = image;
    NSData* imageData = UIImageJPEGRepresentation(postImage, 0.5);
    
    if ([self.qid length] == 0||!self.qid) {
        self.qid = @"0";
    }
    UserModel * userModel = [[UserManager shareInstance]getUserInfo];
    //    NSString * name= userModel.username;
    NSString *myuid=userModel.uid;
    
    ChatContent *messageModel = [[ChatContent alloc] init];
    messageModel.isQuestion = @"0";
    messageModel.message =@"";
    messageModel.MessageType = @"2";
    messageModel.messageDirection =@"1";
    messageModel.qid = self.qid;
    messageModel.dateline = [NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970]];
    messageModel.imageData=imageData;
    messageModel.username = self.userName;
    messageModel.uid = self.touid;
    messageModel.width=[NSString stringWithFormat:@"%f",postImage.size.width];
    messageModel.heigth=[NSString stringWithFormat:@"%f",postImage.size.height];

    [self.dataArray addObject:messageModel];
//    [self.tableView reloadData];
    [self skipTableviewBottom];
    //插入数据库
    NSDictionary *dicMess = [[NSDictionary alloc] initWithObjectsAndKeys:@"send", @"action", myuid, @"myuid",self.toTpye, @"type", self.touid, @"uid", @"", @"message", self.qid, @"qid", self.toMed, @"method", @"图片", @"pic", @"", @"voice",imageData,@"imageData", @"", @"voicelength",messageModel.heigth,@"heigth",messageModel.width,@"width", nil];
//    NSString *jsString = [dicMess JSONString];
    [ChatContent insertChatMessageItem:dicMess Andsuccess:@"0" AndMessageDirection:@"1"];
    
    NSDictionary *dicM=[[NSDictionary alloc]initWithObjectsAndKeys:self.qid,@"qid",self.touid,@"uid",[NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970]],@"dateline",@"",@"message",@"图片",@"pic",@"",@"type",self.userName,@"username",@"",@"voice",@"",@"voicelength",@"",@"method",self.consultType,@"consultType",nil];
    NSString *jsonStringConsult = [dicM JSONString];
    if (self.isFromwhere==kWCEnterIntoConsultChatPeer) {
        [PeerList updatePeerList:jsonStringConsult withReadStatus:@"0" withSuccess:@"1" withMessageDirection:@"1"];
    }
    else if (self.isFromwhere==kWCEnterIntoConsultChatNoPeer)
    {
        [ConsultList updateConsultList:jsonStringConsult withReadStatus:@"0" withSuccess:@"1" withMessageDirection:@"1"];
    }
}
#pragma mark Lable自适应高度
- (void)autosizeFontAndSize:(UILabel *)label withText:(NSString *)text
{
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:label.text];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:5];//调整行间距
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [text length])];
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
    label.attributedText = attributedString;
    [label sizeToFit];
}
#pragma mark 文本自适应高度和宽度
/**
 *  文本自适应高度和宽度（可限定最大宽度）
 *
 *  @param text      传入的文本内容
 *  @param textlabel 显示文本内容的label
 *  @param width     限制最大宽度，高度自适应
 *
 *  @return 返回根据文本内容自适应的label的size；
 */
- (CGSize)autolayoutText:(NSString *)text WithTextLabel:(UILabel *)textlabel WithWidth:(CGFloat )width
{
    
    CGSize size =CGSizeMake(width,0);
    textlabel.lineBreakMode=NSLineBreakByCharWrapping;
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:5];//调整行间距
   
    
    NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:textlabel.font,NSFontAttributeName,paragraphStyle,NSParagraphStyleAttributeName,nil];
    CGSize  actualsize;
    actualsize =[textlabel.text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine  attributes:tdic context:nil].size;
    return actualsize;
}
#pragma mark sendVoiceDelegate
- (void)sendVoice:(NSData *)voiceData withVoicelength:(NSString *)length
{
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"%@message/uploadvoice/",kBaseURL] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        [formData appendPartWithFileData:voiceData name:@"file" fileName:@"voice.caf" mimeType:@"audio/x-caf"];
        
    } error:nil];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSProgress *progress = nil;
    NSURLSessionUploadTask *uploadTask =[manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
        }else
        {
            NSURL *url=[[NSURL alloc]initFileURLWithPath:[[NSBundle mainBundle] pathForResource:@"sendSuccess" ofType:@"caf"]];
            AVAudioPlayer *player=[[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
            self.sendPlay=player;
            [self.sendPlay play];
            NSDictionary * dic = (NSDictionary *)responseObject;
            UserModel * userModel = [[UserManager shareInstance]getUserInfo];
            NSString *myuid=userModel.uid;
            
            if ([self.qid length] == 0||!self.qid) {
                self.qid = @"0";
            }
            NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"send", @"action",myuid , @"from_uid", @"1", @"from_type", self.toTpye, @"to_type", self.touid, @"to_uid", @"", @"message", self.qid, @"qid", [dic objectForKey:@"data"], @"voice", length, @"voicelength", self.qid,@"qid",@"0",@"method",nil];
           AppDelegate *del= (AppDelegate *)[[UIApplication sharedApplication] delegate];
            NSString *jsonString = [dictionary JSONString];
            @try {
                if (del.webSocket.readyState == 1) {
                    [del.webSocket send:jsonString];
                } else {
                    AppDelegate *app=(AppDelegate *)[[UIApplication sharedApplication]delegate];
                    [app webSocket];
                }
            }
            @catch (NSException *exception) {
                MyNSLog("exception = %@", exception);
            }
        }
        [self voiceInsertLocal:voiceData withvoiceLenth:length];

    }];
    [uploadTask resume];
}
- (void)voiceInsertLocal:(NSData *)data withvoiceLenth:(NSString *)length
{
    if ([self.qid length] == 0) {
        self.qid = @"0";
    }
    UserModel * userModel = [[UserManager shareInstance]getUserInfo];
    //    NSString * name= userModel.username;
    NSString *myuid=userModel.uid;

    ChatContent *messageModel = [[ChatContent alloc] init];
    messageModel.isQuestion = @"0";
    messageModel.message = @"";
    messageModel.MessageType = @"3";
    messageModel.messageDirection =@"1";
    messageModel.qid = self.qid;
    messageModel.dateline = [NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970]];
    messageModel.username = self.userName;
    messageModel.uid = self.touid;
    messageModel.voicelength=length;
    messageModel.voiceData=data;
    [self.dataArray addObject:messageModel];
//    [self.tableView reloadData];
    [self skipTableviewBottom];
    //插入数据库
    NSDictionary *dicMess = [[NSDictionary alloc] initWithObjectsAndKeys:@"send", @"action", myuid, @"myuid",self.toTpye, @"type", self.touid, @"uid", @"", @"message", self.qid, @"qid", self.toMed, @"method", @"", @"pic", @"", @"voice", length, @"voicelength",data,@"voiceData", nil];
    [ChatContent insertChatMessageItem:dicMess Andsuccess:@"0" AndMessageDirection:@"1"];
    
    NSDictionary *dicM=[[NSDictionary alloc]initWithObjectsAndKeys:self.qid,@"qid",self.touid,@"uid",[NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970]],@"dateline",@"",@"message",@"",@"pic",@"",@"type",self.userName,@"username",@"语音",@"voice",length,@"voicelength",@"",@"method",self.consultType,@"consultType", nil];
    NSString *jsonStringConsult = [dicM JSONString];
    if (self.isFromwhere==kWCEnterIntoConsultChatPeer) {
        [PeerList updatePeerList:jsonStringConsult withReadStatus:@"0" withSuccess:@"1" withMessageDirection:@"1"];
    }
    else if (self.isFromwhere==kWCEnterIntoConsultChatNoPeer)
    {
        [ConsultList updateConsultList:jsonStringConsult withReadStatus:@"0" withSuccess:@"1" withMessageDirection:@"1"];
    }
    

}
#pragma mark sendMessageDelegate
- (void)sendMessage:(NSString *)message
{
    
    while (1) {
        if ([[message substringWithRange:NSMakeRange(0,1)] isEqualToString:@"\n"])
            message = [message substringFromIndex:1];
        else
            break;
    }
    
    if ([self.qid length] == 0) {
        self.qid = @"0";
    }
    UserModel * userModel = [[UserManager shareInstance]getUserInfo];
    //    NSString * name= userModel.username;
    NSString *myuid=userModel.uid;
    NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"send", @"action", myuid, @"from_uid", @"1", @"from_type", self.toTpye, @"to_type", self.touid, @"to_uid", message, @"message", self.qid, @"qid", @"0", @"method", @"", @"pic", @"", @"voice", @"", @"voicelength", nil];
    
    AppDelegate *del = (AppDelegate *)[UIApplication sharedApplication].delegate;
    NSString *jsonString = [dictionary JSONString];
    @try {
        if (del.webSocket.readyState == 1) {
            [del.webSocket send:jsonString];
        } else {
            AppDelegate *app=(AppDelegate *)[[UIApplication sharedApplication]delegate];
            [app webSocket];
        }
    }
    @catch (NSException *exception) {
        MyNSLog("exception = %@", exception);
    }
    ChatContent *messageModel = [[ChatContent alloc] init];
    messageModel.isQuestion = @"0";
    messageModel.message = message;
    messageModel.MessageType = @"1";
    messageModel.messageDirection =@"1";
    messageModel.qid = self.qid;
    messageModel.dateline = [NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970]];
    messageModel.username = self.userName;
    messageModel.uid = self.touid;
    [self.dataArray addObject:messageModel];
//    [self.tableView reloadData];
    [self skipTableviewBottom];
    //插入数据库
    NSDictionary *dicMess = [[NSDictionary alloc] initWithObjectsAndKeys:@"send", @"action", myuid, @"myuid",self.toTpye, @"type", self.touid, @"uid", message, @"message", self.qid, @"qid", self.toMed, @"method", @"", @"pic", @"", @"voice", @"", @"voicelength", nil];
//    NSString *jsString = [dicMess JSONString];
    [ChatContent insertChatMessageItem:dicMess Andsuccess:@"0" AndMessageDirection:@"1"];
    
    NSString *departmentname;
    if ([self.questionView.department.text isEqualToString:@"不确定科室"]) {
        departmentname=@"不确定科室";
    }
    else
    {
        departmentname=self.questionView.department.text;
    }

    NSDictionary *dicM=[[NSDictionary alloc]initWithObjectsAndKeys:self.qid,@"qid",self.touid,@"uid",[NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970]],@"dateline",message,@"message",@"",@"pic",@"",@"type",self.userName,@"username",@"",@"voice",@"",@"voicelength",@"",@"method",self.consultType,@"consultType",departmentname,@"departmentname", nil];
    NSString *jsonStringConsult = [YXJSON JSONStringWithDictionaryOrArray:dicM];
    if (self.isFromwhere==kWCEnterIntoConsultChatPeer) {
        [PeerList updatePeerList:jsonStringConsult withReadStatus:@"0" withSuccess:@"1" withMessageDirection:@"1"];
    }
    else if (self.isFromwhere==kWCEnterIntoConsultChatNoPeer)
    {
        [ConsultList updateConsultList:jsonStringConsult withReadStatus:@"0" withSuccess:@"1" withMessageDirection:@"1"];
    }
}
#pragma mark selectPhotoDelegate
- (void)selectPhotos
{
//    UIImagePickerController * imagePickerController = [[UIImagePickerController alloc]init];
//    imagePickerController.delegate = self;
//    imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//    imagePickerController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
//    imagePickerController.allowsEditing = YES;
//    [self presentViewController:imagePickerController animated:YES completion:^{
//        
//    }];
    YYImagePickerViewController *picker = [[YYImagePickerViewController alloc] init];
    picker.imagePickerDelegate = self;
    [[LCStatusBarOverlay shared] setCurrentVC:picker];
    [self presentViewController:picker animated:YES completion:nil];
    [keyboardController hiddenCustomKeyboardToolAnimation ];

}
- (void)selectCarmera
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *pickerImage=[[UIImagePickerController alloc] init];
        pickerImage.delegate=self;
        pickerImage.allowsEditing=YES;
        //pickerImage.mediaTypes              默认是静态图片，指定摄像头获取获取数据类型
        pickerImage.sourceType=UIImagePickerControllerSourceTypeCamera;//指定使用相机
        NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
        [user setObject:@"cinemo" forKey:@"cinemo"];
        [self presentViewController:pickerImage animated:YES completion:nil];
        [keyboardController hiddenCustomKeyboardToolAnimation ];

    } else {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"警告" message:@"没有摄像头或摄像头损坏" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
        [alert show];
    }
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:( NSString *)kUTTypeImage]) {
        UIImage *postImage = [info objectForKey:UIImagePickerControllerEditedImage];
        [self loadData1:postImage];

        [picker dismissViewControllerAnimated:YES completion:^{
        }];
    }

}
-(void)imagePickerController:(YYImagePickerViewController *)picker didFinishPickingImages:(UIImage *)image {
    //    YYGridDataModel * model = [images objectAtIndex:0];
    //    MyNSLog("%@",model.image);
    [[LCStatusBarOverlay shared] setCurrentVC:nil];
    [self loadData1:image];
}
- (void)backClicked
{
    [self.navigationController popViewControllerAnimated:YES];
}
/**
 *  结束咨询
 */
- (void)selectOver:(UIButton *)sender
{
    

    
    if ([sender.currentTitle isEqualToString:@"结束咨询"]) {
        if (self.doctoruid&&![self.doctoruid isEqualToString:@"0"]) {
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"你确定要结束该次咨询么？" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
            alert.tag=10;
            [alert show];
        }else
        {
            [self clickover];
        }
    }else if ([sender.currentTitle isEqualToString:@"评价"])
    {
        if (self.doctoruid&&![self.doctoruid isEqualToString:@"0"]) {
            DocCommentViewController *comment;
            if (IPhone6Plus) {
                comment=[[DocCommentViewController alloc]initWithNibName:@"DocCommentViewController6+" bundle:[NSBundle mainBundle]];
            }else{
               comment =[[DocCommentViewController alloc]initWithNibName:@"DocCommentViewController" bundle:[NSBundle mainBundle]];
            }
            comment.doctoruid=self.doctoruid;
            comment.qid=self.qid;
            comment.message=self.questionMessage;
            [self.navigationController pushViewController:comment animated:YES];
        }

    }
    [keyboardController.messageInputView.inputTextView resignFirstResponder];
    [keyboardController hiddenCustomKeyboardToolAnimation ];
    
}
#pragma mark alertDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag==10) {
        
        if (buttonIndex==0) {
            [self clickover];
        }
    }
}
/**
 *  结束咨询
 */
- (void)clickover
{
    [self showActionView];
    if(!self.doctoruid||[self.doctoruid isEqualToString:@"0"])
    {
        self.doctoruid=@"0";
    }
    NSString * requestURL = [NSString stringWithFormat:@"%@/user/questionover/",kBaseURL];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *parameters = @{@"platform": kPlatform,
                                 @"version":kVersion,
                                 @"doctoruid":self.doctoruid,
                                 @"qid":self.qid,
                                 };
    [manager POST:requestURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self hiddenActionView];
        
        NSString *status=[NSString stringWithFormat:@"%@",[responseObject objectForKey:@"status"]];
        if ([status isEqualToString:@"1"]) {
            self.selfOver=@"1";
            keyboardController.messageInputView.hidden=YES;
            if (![self.doctoruid isEqualToString:@"0"]) {
                [rightBtn setTitle:@"评价" forState:UIControlStateNormal];
                self.overView.hidden = NO;
                [UIView animateWithDuration:0.2 animations:^{
                    self.overView.frame=CGRectMake(0, kScreenHeight-64-44, kScreenWidth, 44);
                }];
                UserModel * userModel = [[UserManager shareInstance]getUserInfo];
                NSString * name= userModel.username;
                NSString * string2 = [NSString stringWithFormat:@"%@结束了咨询您的问题",name];
                NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"send", @"action", userModel.uid, @"from_uid", @"1", @"from_type", self.toTpye, @"to_type", self.touid, @"to_uid", string2, @"message", self.qid, @"qid", @"4", @"method", @"", @"pic", @"", @"voice", @"", @"voicelength", nil];
                AppDelegate *del =(AppDelegate *)[[UIApplication sharedApplication]delegate];
                NSString *jsonString = [dictionary JSONString];
                [del.webSocket send:jsonString];
            }
            else
            {
                rightBtn.hidden=YES;
            }
        }else
        {
            [self showCustomHudSingleLine:[responseObject valueForKey:@"msg"]];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hiddenActionView];
    }];

}
#pragma mark OverDelegate
- (void)zanClick
{
    [self showActionView];
    self.overView.zanButton.userInteractionEnabled=NO;

    NSString * requestURL = [NSString stringWithFormat:@"%@/question/good/",kBaseURL];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *parameters = @{@"platform": kPlatform,
                                 @"version":kVersion,
                                 @"qid":self.qid,
                                 };
    [manager POST:requestURL parameters:parameters
          success:^(AFHTTPRequestOperation *operation, id responseObject) {
              [self hiddenActionView];
               NSString *status=[NSString stringWithFormat:@"%@",[responseObject objectForKey:@"status"]];
              if ([status isEqualToString:@"1"]) {
                  UserModel * userModel = [[UserManager shareInstance]getUserInfo];
                  NSString * name= userModel.username;
                  NSString *myuid=userModel.uid;
                  NSString * string2 = [NSString stringWithFormat:@"%@赞了您的回答",name];
                  NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"send", @"action", myuid, @"from_uid", @"1", @"from_type", self.toTpye, @"to_type", self.touid, @"to_uid", string2, @"message", self.qid, @"qid", @"5", @"method", @"", @"pic", @"", @"voice", @"", @"voicelength", nil];
                  
                  AppDelegate *del = (AppDelegate *)[UIApplication sharedApplication].delegate;
                  
                  NSString *jsonString = [dictionary JSONString];
                  [del.webSocket send:jsonString];
                  [self.overView.zanButton setTitle:@"已赞" forState:UIControlStateNormal];
              }else if ([status isEqualToString:@"-1"])
              {
                  UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您已经赞过了" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
                  [alert show];
              }
              self.overView.zanButton.userInteractionEnabled=YES;


          } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
              [self hiddenActionView];
              self.overView.zanButton.userInteractionEnabled=YES;

          }];
}
#pragma  mark 投诉
- (void)reportClick
{
    ReportViewController *report=[[ReportViewController alloc]initWithNibName:@"ReportViewController" bundle:[NSBundle mainBundle]];
    report.objectids=self.doctoruid;
    report.reportType=0;
    report.qid=self.qid;
    report.username=self.userName;
    [self.navigationController pushViewController:report animated:YES];
}
#pragma  mark 点击图片放大
- (void)tapMessageImage:(NSInteger)tag view:(UIView *)view
{
    UIImageView *tempImageview=(UIImageView *)view;
    ChatContent *messageModel = [self.dataArray objectAtIndex:tag];
    //转换成大图
    NSString *bigImageUrl = [[messageModel.pic componentsSeparatedByString:@"@"] objectAtIndex:0];
    
    MyNSLog("messageModel.pic = %@", messageModel.pic);
    MyNSLog("bigImageUrl = %@", bigImageUrl);
    
//    [tempImageview setImageWithURL:[NSURL URLWithString:messageModel.imageUrl]];
    self.picViewController = [[PictureViewController alloc] initWithThumbImage:tempImageview.image imageView:tempImageview largeImagePath:bigImageUrl];
    self.picViewController.delegate = self;
    
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:tag inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
}

-(void)PictureViewDidDismiss{
    self.picViewController.imageView=nil;
    self.picViewController = nil;
}
#pragma  mark 销毁界面，清除通知
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
    //    [instance release];
    //    [super dealloc];
}
#pragma  mark   SendJiahaodanDelegate
- (void)sendAccept:(NSInteger)tag
{
    [self showActionView];
    NSIndexPath *indexpath=[NSIndexPath indexPathForRow:tag inSection:0];
    MethodViewCell *methodcell=(MethodViewCell *)[self.tableView cellForRowAtIndexPath:indexpath];
    methodcell.accept.userInteractionEnabled=NO;
    methodcell.reject.userInteractionEnabled=NO;

    ChatContent *chat=[self.dataArray objectAtIndex:tag];
    NSString *postURL=[NSString stringWithFormat:@"%@jiahao/accept/",kBaseURL];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *parmars=@{
                            @"platform": kPlatform,
                            @"version":kVersion,
                            @"accept":@"1",
                            @"id":methodcell.registeredId,
                            };
    [manager POST:postURL parameters:parmars success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self hiddenActionView];
        NSString *status=[NSString stringWithFormat:@"%@",[responseObject valueForKey:@"status"]];
        if ([status isEqualToString:@"1"]) {
            
            UserModel * userModel = [[UserManager shareInstance]getUserInfo];
            NSString *myuid=userModel.uid;
            NSUserDefaults *userDefault=[NSUserDefaults standardUserDefaults];
            [userDefault setObject:@"1" forKey:[NSString stringWithFormat:@"%@%@",methodcell.registeredId,myuid]];
            [userDefault synchronize];
            [methodcell.accept setTitle:@"已接受" forState:UIControlStateNormal];
            methodcell.accept.userInteractionEnabled=NO;
            methodcell.reject.userInteractionEnabled=NO;
            
            NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"send", @"action", myuid, @"from_uid", @"1", @"from_type", self.toTpye, @"to_type", self.touid, @"to_uid", @"用户接受了您的挂号单", @"message", self.qid, @"qid", @"7", @"method", @"", @"pic", @"", @"voice", @"", @"voicelength", nil];
            AppDelegate *del = (AppDelegate *)[UIApplication sharedApplication].delegate;
            NSString *jsonString = [dictionary JSONString];
            @try {
                if (del.webSocket.readyState == 1) {
                    [del.webSocket send:jsonString];
                } else {
                    AppDelegate *app=(AppDelegate *)[[UIApplication sharedApplication]delegate];
                    [app webSocket];
                }
            }
            @catch (NSException *exception) {
                MyNSLog("exception = %@", exception);
            }
            //
            
            //存入本地数据库
            ChatContent *messageModel = [[ChatContent alloc] init];
            messageModel.isQuestion = @"0";
            NSArray *info=[chat.message componentsSeparatedByString:@","];
            NSString *myname=[[NSUserDefaults standardUserDefaults]valueForKey:[NSString stringWithFormat:@"%@realname",myuid]];
            messageModel.message=[NSString stringWithFormat:@"%@，这是你的加号确认码：%@，请于%@来%@找%@医生。请妥善保管该信息，以作确认！",myname,[[responseObject valueForKey:@"data"] valueForKey:@"appiontmentcode"],[info objectAtIndex:1],[info objectAtIndex:0],self.userName];
            messageModel.MessageType = @"1";
            messageModel.messageDirection =@"2";
            messageModel.qid = self.qid;
            messageModel.dateline = [NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970]];
            messageModel.username = self.userName;
            messageModel.uid = self.touid;
                        //插入数据库
            NSDictionary *dicMess = [[NSDictionary alloc] initWithObjectsAndKeys:@"send", @"action", myuid, @"myuid",self.toTpye, @"type", self.touid, @"uid", messageModel.message, @"message", self.qid, @"qid",[NSString stringWithFormat:@"%.f", [[NSDate date] timeIntervalSince1970]*10000],@"dateline", self.toMed, @"method", @"", @"pic", @"", @"voice", @"", @"voicelength", nil];
            if ([ChatContent insertChatMessageItem:[YXJSON JSONStringWithDictionaryOrArray:dicMess] Andsuccess:@"0" AndMessageDirection:@"2"]) {
                [self.dataArray addObject:messageModel];
                //    [self.tableView reloadData];
                [self skipTableviewBottom];
            }
            ;
//            
            
            NSDictionary *dicM=[[NSDictionary alloc]initWithObjectsAndKeys:self.qid,@"qid",self.touid,@"uid",[NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970]],@"dateline",messageModel.message,@"message",@"",@"pic",@"",@"type",self.userName,@"username",@"",@"voice",@"",@"voicelength",@"",@"method", nil];
            NSString *jsonStringConsult = [YXJSON JSONStringWithDictionaryOrArray:dicM];
            [ConsultList updateConsultList:jsonStringConsult withReadStatus:@"0" withSuccess:@"1" withMessageDirection:@"1"];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hiddenActionView];
        methodcell.accept.userInteractionEnabled=YES;
        methodcell.reject.userInteractionEnabled=YES;
    }];
    
}
- (void)sendReject:(NSInteger)tag
{
    UserModel * userModel = [[UserManager shareInstance]getUserInfo];
    //    NSString * name= userModel.username;
    NSString *myuid=userModel.uid;
    NSIndexPath *indexpath=[NSIndexPath indexPathForRow:tag inSection:0];

    MethodViewCell *methodcell=(MethodViewCell *)[self.tableView cellForRowAtIndexPath:indexpath];
    NSUserDefaults *userDefault=[NSUserDefaults standardUserDefaults];
    [userDefault setObject:@"2" forKey:[NSString stringWithFormat:@"%@%@",methodcell.registeredId,myuid]];
    [userDefault synchronize];
    methodcell.accept.userInteractionEnabled=NO;
    methodcell.reject.userInteractionEnabled=NO;
    [methodcell.reject setTitle:@"已拒绝" forState:UIControlStateNormal];
    
    [self.tableView reloadData];
    
    NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"send", @"action", myuid, @"from_uid", @"1", @"from_type", self.toTpye, @"to_type", self.touid, @"to_uid", @"用户拒绝了您的挂号单", @"message", self.qid, @"qid", @"8", @"method", @"", @"pic", @"", @"voice", @"", @"voicelength", nil];
    
    AppDelegate *del = (AppDelegate *)[UIApplication sharedApplication].delegate;
    NSString *jsonString = [dictionary JSONString];
    @try {
        if (del.webSocket.readyState == 1) {
            [del.webSocket send:jsonString];
        } else {
            AppDelegate *app=(AppDelegate *)[[UIApplication sharedApplication]delegate];
            [app webSocket];        }
    }
    @catch (NSException *exception) {
        MyNSLog("exception = %@", exception);
    }
}
/**
 *  放大照片
 */
-(void)tapQuestionImage:(UITapGestureRecognizer *)tap
{
    XHImageViewer *imageViewer = [[XHImageViewer alloc] init];
    imageViewer.delegate = self;
    [imageViewer showWithImageViews:Views selectedView:(UIImageView *)tap.view];
}
- (void)doloadMoreMessage
{
    pagecount=pagecount+1;
    if (self.isFromwhere==kWCEnterIntoConsultChatPeer) {
        self.dataArray=[ChatContent readItemFromChatContentTable:0 count:pagecount*20 withUid:self.touid];
        [self.tableView headerEndRefreshing];
        [self.tableView reloadData];

//        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:20 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];


    }else if(self.isFromwhere==kWCEnterIntoConsultChatNoPeer)
    {
    self.dataArray=[ChatContent readItemFromChatContentTable:0 count:pagecount*20 withQid:self.qid];
        [self.tableView headerEndRefreshing];
        [self.tableView reloadData];

//        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:20 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
    }
}
//举报时选择聊天记录之后点击完成
-(void)doneButtonClick:(UIButton *)button
{
    NSMutableDictionary *reportDict = [[NSMutableDictionary alloc] init];
    for (int i=0; i<[self.reportArray count]; i++) {
        @try {
            //将MessageModel转成字典放到一个字典里
            [reportDict setObject:[self transformDictWithMessageModel:[self.reportArray objectAtIndex:i]] forKey:[NSString stringWithFormat:@"%d", i]];
        }
        @catch (NSException *exception) {
            MyNSLog("exception = %@", exception);
        }
    }
    //将字典转成JSONString
    NSString *reportString = [reportDict JSONString];
    NSDictionary *messageDict = [[NSDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"%ld", [self.reportArray count]], @"messageCount", reportString, @"reportMessage", nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"SETREPORTSTRING" object:nil userInfo:messageDict];
    [self.navigationController popViewControllerAnimated:YES];
}
-(NSDictionary *)transformDictWithMessageModel:(ChatContent *)messageModel
{
    NSDictionary *tempDict = [[NSDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"%@", messageModel.messageType], @"messageType", [NSString stringWithFormat:@"%@", messageModel.messageDirection], @"messageDirection", messageModel.action ? : @"", @"action", messageModel.dateline ? : @"", @"dateline", messageModel.message ? : @"", @"message", messageModel.pic ? : @"", @"pic", messageModel.qid ? : @"", @"qid", messageModel.type ? : @"", @"type", messageModel.uid ? : @"", @"uid", messageModel.username ? : @"", @"username", messageModel.voice ? : @"", @"voice", messageModel.voicelength ? : @"", @"voicelength", messageModel.departmentname ? : @"", @"departmentname", messageModel.isQuestion ? : @"", @"isQuestion", messageModel.method ? : @"", @"method", nil];
    return tempDict;
}
#pragma  mark IfTweetlabelDelegate
-(void)clickURL:(NSString *)url
{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://%@",url]]];
}
- (void)clickTel:(NSString *)telphone
{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"telprompt://%@",telphone]]];
}
#pragma  Mark ------relatedIssuseDelegate
- (void)clickRelatedIssuse:(NSDictionary *)dic
{
    RelatedQustionsViewController *related=[[RelatedQustionsViewController alloc]initWithNibName:@"RelatedQustionsViewController" bundle:[NSBundle mainBundle]];
    related.qid=[dic valueForKey:@"qid"];
    related.questionInfo=dic;
    [self.navigationController pushViewController:related animated:YES];
}
- (void)clickMoreIssueInfo:(NSString *)keyword
{
    RelatedListViewController *related=[[RelatedListViewController alloc]initWithNibName:@"RelatedListViewController" bundle:[NSBundle mainBundle]];
    related.keyword=keyword;
    [self.navigationController pushViewController:related animated:YES];

}
/**
 *  长按复制
  */
- (void)dolongPress:(UILongPressGestureRecognizer *)recognizer
{
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        
        [recognizer.view becomeFirstResponder];
        UIMenuController *menu = [UIMenuController sharedMenuController];
        [menu setTargetRect:recognizer.view.frame inView:[recognizer.view superview]];
        boarString=[(IFTweetLabel *)recognizer.view text];
        [menu setMenuVisible:YES animated:YES];
    }
}
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender{
    //    return (action == @selector(copy:));
    if (action == @selector(copy:))
    {
        return YES;
    }
    return NO;
}
- (void)copy:(id)sender {
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    if ([boarString length] == 0){
        
    }else{
    [pasteboard setString:boarString];
    }
}

@end
